Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to 'cout' the correct number of decimal places of a double value?

I need help on keeping the precision of a double. If I assign a literal to a double, the actual value was truncated.

int main() {     double x = 7.40200133400;     std::cout << x << "\n"; } 

For the above code snippet, the output was 7.402
Is there a way to prevent this type of truncation? Or is there a way to calculate exactly how many floating points for a double? For example, number_of_decimal(x) would give 11, since the input is unknown at run-time so I can't use setprecision().


I think I should change my question to: How to convert a double to a string without truncating the floating points. i.e.

#include <iostream> #include <string> #include <sstream>  template<typename T> std::string type_to_string( T data ) {     std::ostringstream o;     o << data;     return o.str(); }  int main() {     double x = 7.40200;     std::cout << type_to_string( x ) << "\n"; } 

The expected output should be 7.40200 but the actual result was 7.402. So how can I work around this problem? Any idea?

like image 662
Chan Avatar asked Nov 18 '10 17:11

Chan


People also ask

How do you know how many decimal places are in a double?

There are no decimal digits in a double. There are binary digits. Another way of looking at it: A double, at the hardware level on Intel platforms, is a 52-bit integer. And there is an 11-bit number that tells you where to put the decimal point.

How do you find the correct number of decimal places?

For the number of decimal places stated, count that number of digits to the right of the decimal and underline it. The next number to its right is called the 'rounder decider'. If the 'rounder decider' is 5 or more, then round the previous digit up by 1.

How do you correct decimal places in C++?

Decimal Places This can be done using the fixed keyword before the setprecision() method. When the fixed keyword is used, the argument in the setprecision() function specifies the number of decimal places to be printed in the output.

What is the number 2.738 correct to 2 decimal places?

What is 2.738 Round to Two Decimal Places? In the given number 2.738, the digit at the thousandths place is 8, so we will add 1 to the hundredths place digit. So, 3+1=4. Therefore, the value of 2.738 round to two decimal places is 2.74.


1 Answers

Due to the fact the float and double are internally stored in binary, the literal 7.40200133400 actually stands for the number 7.40200133400000037653398976544849574565887451171875

...so how much precision do you really want? :-)

#include <iomanip>     int main() {     double x = 7.40200133400;     std::cout << std::setprecision(51) << x << "\n"; } 

And yes, this program really prints 7.40200133400000037653398976544849574565887451171875!

like image 153
fredoverflow Avatar answered Sep 25 '22 15:09

fredoverflow