0

Is there any way in C++ (or boost lib) to show a given number digits of fraction part? But I don't want to print the trailing 0 in fraction part (eg. 1.000, 1.500). See this case:

cout << std::setprecision(3) << 5.0/7.0 << endl;    //  0.714
cout << std::setprecision(3) << 12.0/7.0 << endl;   //  1.71
cout << std::setprecision(3) << 7.0/7.0 << endl;    //  1
cout << std::setprecision(3) << 10.5/7.0 << endl;   //  1.5

The problem is setprecision prints line 1 and line 2 differently, where I want to have both lines print 0.714 and 1.714. And still keep line 3 and line 4 1 and 1.5.

1
  • Using fixed precision flag std::fixed to get exact 3-digit fraction part, then convert it to double/float, and convert it back to string to get rid of trailing zero's can achieve the goal too. But isn't there a clean way to do it?
    – Stan
    Commented Oct 2, 2013 at 13:03

1 Answer 1

1

How about something like:

#include <cmath>
using namespace std;

cout << setprecision(ceil(log10(floor(x))+3) << x;

Not exactly fast, but the idea is to figure out how many digits the integer part of x requires, then add the number of decimal places you're interested in to that. You could even write your own manipulator to do that if you were really serious about it.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.