DrPepperJo
DrPepperJo

Reputation: 722

c++ float to string non-fixed precision after decimal

Is there an easy way to set a non-fixed precision after decimal in c++ when converting floats to strings?

What std::setprecision( 2 ) does is:

1.00000 -> 1
1.23456 -> 1.2
12.3456 -> 12
12.3000 -> 12.3

What std::fixed adds to it is:

1.00000 -> 1.00
1.23456 -> 1.20
12.3456 -> 12.34
12.3000 -> 12.30

What I want to do is:

1.00000 -> 1
1.23456 -> 1.23
12.3456 -> 12.34
12.3000 -> 12.3

Upvotes: 0

Views: 114

Answers (1)

wally
wally

Reputation: 11002

The following rounds to two decimals and then uses the default precision:

#include <iostream>
#include <iomanip>
#include <cmath>

int main()
{
    double vals[]{1.00000, 1.23456, 12.3456, 12.3000};
    for(auto i : vals) {
        i = std::round(i * 100) / 100;
        std::cout << i << '\n';
    }
}

Produces:

1
1.23
12.35
12.3

Upvotes: 1

Related Questions