<kd********@yahoo.com> wrote in message
news:11**********************@z14g2000cwz.googlegr oups.com...
Does anyone have any sample code on how to round off a float to x
digits? say for example rounding 3.1415 to 3.1?
Any help would be appreciated. I am learning C++ and have not found
this info on the net (though it might be out there)
o Floating point formats are almost always in binary, not in decimal.
Many decimal numbers cannot be exactly represented by the underlying
floating point format - 3.1 is an example. Rounding to a certain number of
binary digits is very different from rounding to a certain number of decimal
digits.
o Rounding of floating point values should only done with the final
result for purposes of presenting to humans. Rounding intermediate values is
a bad idea, only useful for demonstrating how badly it can trash your
results. Why this is true is not so easy to grasp, many smart people have
fallen victim to misunderstanding the need to use all the precision
available. Check out Prof. Kahan's work on this (google for "Kahan floating
point").
o A corollary to the above rule is use the maximum precision available on
your machine. For x86, that would be 80 bit long doubles. (Unfortunately,
some popular C++ compilers do not support 80 bit long doubles, they max out
at 64. Digital Mars C++ supports 80 bit long doubles.) You can get away with
lesser precision if speed and memory consumption are paramount and accurate
results are not (such as in game graphics engines).
o Rounding to a certain number of digits for display of the final result
is handilly performed by the 'precision' field in the printf format family
of functions. For example,
printf("%.8g\n", d);
prints d with 8 digits of precision. Note the decimal point before the 8.
Hope this helps!
-Walter
www.digitalmars.com free C, C++, D compilers
"code of the nerds"