I am trying to print a maximum of 4 digits after a decimal point in C ++ (using streams). So if the number does not need 4 digits after the decimal, I want him to use only the number of decimal places that he really needs.
Examples:
1.12345 -> 1.1234 1.0 -> 1 1.12 -> 1.12 1.12345789 -> 1.1234 123.123 -> 123.123 123.123456 -> 123.1234
I tried std::setprecision(4) , but this sets the number of significant digits and does not work in the test case:
123.123456 gives 123.1
I also tried giving std::fixed along with std::setprecision(4) , but this gives a fixed number of digits after the decimal, even if it is not needed:
1.0 gives 1.0000
It seems that std::defaultfloat is the one I need, not fixed or exponential. But it does not seem to print the number of digits after the decimal point and does not have the ability to significant digits.
source share