I see many questions about the precision number for floating point numbers but specifically I want to know why this code
#include <iostream> #include <stdlib.h> int main() { int a = 5; int b = 10; std::cout.precision(4); std::cout << (float)a/(float)b << "\n"; return 0; }
shows 0.5
? I expect to see 0.5000
. Is it because of the original integer data types?
You can set the precision directly on std::cout and use the std::fixed format specifier. double d = 3.14159265358979; cout. precision(17); cout << "Pi: " << fixed << d << endl; You can #include <limits> to get the maximum precision of a float or double.
print( '{:,g}'. format( X ) worked for me to output 3 where X = 6 / 2 and when X = 5 / 2 I got an output of 2.5 as expected. old question, but.. print("%s"%3.140) gives you what you want.
By using the setprecision function, we can get the desired precise value of a floating-point or a double value by providing the exact number of decimal places. If an argument n is passed to the setprecision() function, then it will give n significant digits of the number without losing any information.
#include <iostream> #include <stdlib.h> #include <iomanip> int main() { int a = 5; int b = 10; std::cout << std::fixed; std::cout << std::setprecision(4); std::cout << (float)a/(float)b << "\n"; return 0; }
You need to pass std::fixed
manipulator to cout
in order to show trailing zeroes.
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