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
5
  • 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? Commented Sep 20, 2017 at 16:34
  • Please, show the code where you are converting floats to strings. Commented Sep 20, 2017 at 16:35
  • Please post a minimal reproducible example. It is not clear what you have now vs. what you want. Commented Sep 20, 2017 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. Commented Sep 20, 2017 at 16:39
  • Have a look at this answer. But honestly, with a short program showing what you are trying to do this would be lot easier to answer. Commented Sep 20, 2017 at 16:48

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.