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()?
" Does ANSI C++ specification allow to display anything for floating numbers when std::cout is used without std::setprecision()?" yes it does.
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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With