Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
C++
How do you round off a float?
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="Walter, post: 1524863"] 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 [URL="http://www.digitalmars.com"]www.digitalmars.com[/URL] free C, C++, D compilers "code of the nerds" [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
C++
How do you round off a float?
Top