1

Let's say I have some calculations as below:

double a = 99.44, result;

result = 99.44 / 100 * 99.5;

The value stored in result will be 98.9428. How do I round the value into 98.94 and store into "result" ?

The setprecision method only can round the value during cout, but I want the value stored to be rounded for further calculations.

hatched
  • 713
  • 1
  • 5
  • 25

2 Answers2

3

You can use the following algorithm:

  • multiply with 100
  • round to nearest integer
  • divide by 100

This algorithm has problems with big values that are very close to maximum representable as the multiplication may overflow.

Another approach is to use the stream manipulators as you would with std::cout but stream into a string, and then convert that string back into a floating point number. This is much slower, but has no caveat mentioned above.

eerorika
  • 181,943
  • 10
  • 144
  • 256
  • Refuted [here](https://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java/12684082#12684082). – user207421 Oct 05 '17 at 08:33
  • 2
    @EJP I think your test is faulty. Even `(0.03 % 0.01) != 0.0)` is true. You're ignoring the fact that not all numbers can be represented by floating point numbers. The point of rounding (and really, doing **any** calculation on) a floating point (whether to an integer, or to a decimal place) is to get the value that is the closest representable value to the accurate result; sometimes with some error. Now, perhaps this algorithm is wrong for that, but your test doesn't seem to prove it. – eerorika Oct 05 '17 at 10:05
  • 'The fact that not all numbers can be represented by floating point numbers' *is the point of the test*. That's what it proves. If there was such a thing as a floating-point representation of 0.01 correct to exactly two decimal places, it would pass. It doesn't. QED. – user207421 Oct 23 '17 at 08:17
  • @EJP I see. Then it refutes nothing about my suggested algorithm(s). – eerorika Oct 23 '17 at 09:28
  • Yes it does. Your suggested algorithm relies on FP being able to represent numbers such as 0.01 exactly. – user207421 Oct 23 '17 at 22:40
  • @EJP The algorithm relies on no such thing. – eerorika Oct 24 '17 at 00:16
2

You can't. Floating-point variables don't have decimal places: they have binary places, which are incommensurable with decimal places.

If you want decimal places, you have to use a decimal radix, e.g. when formatting for output.

user207421
  • 289,834
  • 37
  • 266
  • 440