0

There is variable amount of double type with value 269.80000000000001

I need truncate it to 2 decimals.

double result1 = round(amount * 100) / 100;
double result2 = (double)trunc(amount * 100) / 100;

after that result1 and result2 is still equals 269.80000000000001

Please tell me how truncate it to 2 decimals and why methods above does not work?

greenif
  • 1,055
  • 1
  • 12
  • 25
  • 2
    269.8 is not representable by `double`: http://www.binaryconvert.com/result_double.html?decimal=050054057046056 – Daniel Langr Mar 21 '19 at 10:16
  • 2
    Try to represent `0.8` as the sum of negative powers of `2` (`0.5`, `0.25`, `0.125`, etc). You'll find it is an infinite series, in exactly the same way that `1/3` is an infinite series in decimal (`0.3333.....`). That is the reason that typical floating point types cannot exactly represent a value like `0.8`. Or `269.8`. They only represent an approximation, as you are seeing. – Peter Mar 21 '19 at 10:25
  • it doesnt matter that you did these operations, the result is still stored to a double variable. They would have to be displayed till the required precision regardless., try storing the result to a float variable . – Valkyrie Mar 21 '19 at 10:38
  • Out of interest, why do you need it truncated? – Bathsheba Mar 21 '19 at 10:47
  • Don't store amounts in floating point variables. Instead store it in integer in minor units and do calculations on those – yachoor Mar 21 '19 at 11:00
  • Just print it to two decimal places to get output of `269.80`. That doesn't change the value to be equal to `296.8`. It simply displays it in way that (arguably) better suits a human. – Peter Mar 21 '19 at 11:00
  • Made calculations without truncation. And format rounding at output std::ostringstream streamConvertor; streamConvertor << std::setprecision(2) << std::fixed << value; – greenif Mar 22 '19 at 07:25

0 Answers0