Question

I know how to print a rounded number to N decimals like this:

using namespace std;

cout << setprecision(N) << fixed;
float k = 1.23441;
cout << k;

Let's use for example N = 2.

This will output 1.23, which is good, but if k is 1.0012, it will output 1.00, and I want it to output 1. If k is 1.1045, it will output 1.10, and I want it to output 1.1, so I want to round to 2 decimals and remove the unnecesary zeroes.

How can I do so?

Was it helpful?

Solution

Actually, the problem is not setprecision, it's fixed. With fixed you explicitly asked to have a fixed number of digits!

If you use setprecision without fixed, it'll do exactly what you are asking for:

#include <iostream>
#include <iomanip>

int main() {
    double const number = 123.456789;
    for (int i = 0; i != 15; ++i) { std::cout << i << ": " << std::setprecision(i) << number << "\n"; }
    return 0;
}

Will output:

0: 1e+02
1: 1e+02
2: 1.2e+02
3: 123
4: 123.5
5: 123.46
6: 123.457
7: 123.4568
8: 123.45679
9: 123.456789
10: 123.456789
11: 123.456789
12: 123.456789
13: 123.456789
14: 123.456789

You can find documentation on the different modes here:

  • fixed
  • scientific
  • hexfloat
  • defaultfloat

And what you want is defaultfloat, which as the name implies is the default.

OTHER TIPS

The appearance of (seemingly) redundant zeros at the end should not be suppressed. Consider

1.2
1.23
1.234
1.2000
1.2300
1.2340

The first number says that it is 1.2 +/- 0.05, the next one says it's 1.23 +/- 0.005 and the third one, 1.234 +/- 0.0005.

In constrast, all of the following numbers indicate a precision that isn't farther off than 0.00005.

So, removing trailing zeros in a decimal fraction is not a way to present date more readable; usually the lack of trailing digits is understood to indicate a lack of precision in the computation.

Later

The removal of characters from a string resulting from a formatted conversion must be coded explicitly if the conversion does not meet your requirements. Therefore, convert to a string using the format that's closest to your requirements, and then post-process the string.

If the string is the result of some fixed-point formatted conversion, according to the pattern \d+\.\d+, you can reverse-scan the string from the end (hint: string::find_last_not_of). Do you want to truncate 1.000 to 1.0 or 1. or 1? The last form will even insinuate that the value is an integer, which it isn't.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top