|
From: Jason H. <jas...@bt...> - 2001-10-31 04:14:37
|
Relying on type conversions to crop a number to a specific number of decimal places isn't the best way of going about it, although it is usualy quite effective. There are some mathematical functions for dealing with rounding and integer values, and the one I suggest you look at is abs(), or fabs(). abs() is an overloaded function available in C++ whereas fabs() is specificaly for float values (it actualy uses a double). You may already know this, but multiplying by a power of ten before apply abs and then dividing by that value again will allow you to choose to how many decimal places you want to work. Adding .5 after the multiplication will ensure proper rounding also. The problem you are having with the lack of accuracy in the float is most likely due to the inherant flaw in floating point representation. They cannot represent all values in thier range dead on, and there will always be a certain amount of rounding errors in some calculations. There's not a lot you can do about it. There are different ways of representing numbers, but I doubt you need that level of accuracy. What you can do with cout, or when converting a number to a string is to set the number of decimal places it will display, so the extra 0001 will be chopped off. For cout or other stream operations I suggest you look at the precision() method. If you are using sprintf then something like - sprintf(strarray, "%1.2f", my_float); which should (I think) produce a number of at least 1 significant digit with rounding to 2 decimal places. Experiment with it a little to see what produces the results you want. Jason. Disclaimer: This information is meant as a guide, and may not be interpreted as gospel truth. I try to reasonably, but not overly, accurate. ----- Original Message ----- From: "Brian McCall" <str...@ho...> To: <dev...@li...> Sent: Wednesday, October 31, 2001 2:19 AM Subject: [Dev-C++] Damn floats > I'm having much trouble trying to manipulate floats. I try to truncate the > part left of the decimal like so: > > float num1 = 45.34; > int num2 = int (num1); > num1 -= float (num2); > > But when I display num1 (cout<<num1), I get something like 0.3400001. > What am I supposed to do about this? > > Actually, the reason I am doing this is as part of a function that assigns a > float to a string, i.e., storing num1 in something like strNum1 as "45.34" > (apstring strNum1; strNum1 = num1). > > Any ideas on either of these two problems? > > _________________________________________________________________ > Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp > > > _______________________________________________ > Dev-cpp-users mailing list > Dev...@li... > https://lists.sourceforge.net/lists/listinfo/dev-cpp-users |