C++ how to show exact digits of fraction part

1.7k Views Asked by At

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

There are 1 best solutions below

0
Drew Hall On

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.