Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::cout with floating number

Tags:

c++

I'm using visual studio 2015 to print two floating numbers:

double d1 = 1.5;
double d2 = 123456.789;

std::cout << "value1: " << d1 << std::endl;
std::cout << "value2: " << d2 << std::endl;

std::cout << "maximum number of significant decimal digits (value1): " << -std::log10(std::nextafter(d1, std::numeric_limits<double>::max()) - d1) << std::endl;
std::cout << "maximum number of significant decimal digits (value2): " << -std::log10(std::nextafter(d2, std::numeric_limits<double>::max()) - d2) << std::endl;

This prints the following:

value1: 1.5
value2: 123457
maximum number of significant decimal digits (value1): 15.6536
maximum number of significant decimal digits (value2): 10.8371

Why 123457 is print out for value 123456.789? Does ANSI C++ specification allow to display anything for floating numbers when std::cout is used without std::setprecision()?

like image 694
Daniel Laügt Avatar asked Nov 22 '15 12:11

Daniel Laügt


People also ask

Does cout round float?

" Does ANSI C++ specification allow to display anything for floating numbers when std::cout is used without std::setprecision()?" yes it does.

How do you print a floating value in CPP?

In order to force C++ to display our floating-point numbers in the scientific format regardless of the size of the number, we use the format specifier scientific inside of cout .

How do you return a float value in C++?

To return a float out of a function with long return type, the float value must be converted to long. When converting a float value to long, the decimal value of float will be truncated off, leading to a loss in the value of float, which is allowed by C++ compiler.

How do I fix the number of 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.


1 Answers

The rounding off happens because of the C++ standard which can be seen by writing std::cout<<std::cout.precision();

The output screen will show 6 which tells that the default number of significant digits which will be printed by cout statement is 6. That is why it automatically rounds off the floating number to 6 digits.

like image 155
incomplet_ Avatar answered Oct 12 '22 01:10

incomplet_