Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting minimum number of decimal places for std::ostream precision

Is there a way to set the "minimum" number of decimal places that a std::ostream will output?

For example, say I have two unknown double variables that I want to print (values added here for the sake of illustration):

double a = 0;
double b = 0.123456789;

I can set my maximum decimal precision so that I output b exactly

std::cout << std::setprecision(9) << b << std::endl;
>>> 0.123456789

Is there a way to set a "minimum" precision (a minimum number of decimal places), while retaining the "maximum" precision, so that

std::cout << a << std::endl << b << std::endl;

yields

0.0
0.123456789

not

0
0.123456789

?

Thanks! Phil


the short answer to this is "No". The stream has only one precision setting, with no facility to differentiate between maximum and minimum precision. Thanks all for your generous advice!

like image 878
Phil Boltt Avatar asked Mar 22 '10 02:03

Phil Boltt


People also ask

How do I limit decimal places in C++?

The C++ setprecision can also be used to format only the decimal places instead of the whole floating-point or double value. This can be done using the fixed keyword before the setprecision() method.

How do I get 6 decimal places in C++?

setprecision() to Specify Decimal Points We can specify the number of decimal points to print in cout by using the setprecision() function. This function is defined in the iomanip header file, which stands for input/output manipulation.

How do you specify precision in C++?

std::setprecision Sets the decimal precision to be used to format floating-point values on output operations. Behaves as if member precision were called with n as argument on the stream on which it is inserted/extracted as a manipulator (it can be inserted/extracted on input streams or output streams).

How do you restrict a float upto 2 decimal places?

We will use %. 2f to limit a given floating-point number to two decimal places.


2 Answers

cout << setprecision(1) << fixed << d << endl;

Used fixed after setprecision.

Edit: This is what you want. It would change precision based on d.

cout << setprecision(d?9:1) << fixed << d << endl;
like image 51
Sameer Avatar answered Sep 20 '22 04:09

Sameer


I do not think there is a way to achieve what you are asking without turning the number into a string (with high precision), and stripping off the trailing zeros.

This is appropriate, because just because there are trailing zeros doesn't mean there isn't precision there, and the run-time can't tell that.

For example, if I measure the weight of an object with a cheap scale, it may be 1.0 kgs.

If I weigh it with a high-accuracy scale, it may be 1.00000 kgs. Just because there are trailing zeros, doesn't mean that accuracy should be discarded.

like image 43
Oddthinking Avatar answered Sep 18 '22 04:09

Oddthinking