0

Is there a way within C++ of setting a definitive amount of decimal points to a float value? for example if i were to record multiple times as float values, i would most likely generate different results (in terms of number of decimal places) and would like to generate numbers of the same lengths i.e if a number were to return as 1.33 and there are other numbers returning as say 1.333 i would like to make the first result read as 1.330.

I understand there are methods of limiting the amount of decimal places such as setprecision() but i do not want to loose accuracy of my times.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740

2 Answers2

4

You seem to confuse two things: the actual precision of floating point calculations in C++, and formatting of float (or double, or long double) values when printing with C++ streams (like cout, for example).

The first depends on the hardware/platform, and you cannot control it, apart from choosing between float and double. If you need better precision than what long double can give you, you need a library for arbitrary precision maths, for example GMPLIB.

Controlling number of digits after dot when printing/formatting is easier, see for example this question: Set the digits after decimal point

Community
  • 1
  • 1
piokuc
  • 25,594
  • 11
  • 72
  • 102
  • The *easiest* way to get more precision that what `float`s give you is to use `double` or `long double`. – dan04 Dec 16 '13 at 23:17
1

If your need is to limit the digits after the decimal point whether of folat, double or long double then is way is to use (setprecision). When you use it seperately it will be including the digits before decimal point as well and also if the digits after the decimal point are less than the precision being set,it will not add a zero after them. And the solution is to use fixed and showpoint. So if you want to set the precision to 3 digits after the decimal point then write this line before displaying or computing the values.

cout<<fixed<<showpoint<<setprecision(3);
Ali Raza
  • 191
  • 2
  • 12