0

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
DrPepperJo
  • 632
  • 1
  • 5
  • 19
  • 1
    I don't get it. Aren't you asking for a fixed precision in you example (2 in this case)? What do you mean by non fixed precision? – dtell Sep 20 '17 at 16:34
  • Please, show the code where you are converting floats to strings. – KelvinS Sep 20 '17 at 16:35
  • Please post a [mcve]. It is not clear what you have now vs. what you want. – wally Sep 20 '17 at 16:39
  • I've changed the example a little bit, to make it more clear. I want to set the precision only for the digits after the decimal, not for all digits in the number, but don't want trailing zeros. – DrPepperJo Sep 20 '17 at 16:39
  • Have a look at [this answer](https://stackoverflow.com/a/17342002/1460794). But honestly, with a short program showing what you are trying to do this would be lot easier to answer. – wally Sep 20 '17 at 16:48

1 Answers1

1

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
wally
  • 10,717
  • 5
  • 39
  • 72