0

I've noticed a weird behaviour while adding two double values, one negative and one positive.

var eighteenPointFive = -18.5;
var nineteenPointFour = 19.4;

var eighteenPointFour = -18.4;
var nineteenPointFive = 19.5;

Console.WriteLine(eighteenPointFive + nineteenPointFour); // prints 0.899999999999999 (why not 0.9?)

Console.WriteLine(eighteenPointFour + nineteenPointFive); // prints 1.1

Why is there a difference in the number of digits after the decimal point in both cases?.

snippetkid
  • 282
  • 4
  • 16
  • 6
    because double is type of floating-point. see [Why Are Floating Point Numbers Inaccurate?](http://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate) – M.kazem Akhgary Jun 18 '15 at 10:17
  • http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html – Hamid Pourjam Jun 18 '15 at 10:21
  • 1
    Simpler and classical example: https://dotnetfiddle.net/79FLWb: 0.1 + 0.2 != 0.3 – xanatos Jun 18 '15 at 10:24
  • 2
    Use decimals instead of doubles. Decimal literals have the `m` suffix, eg `-18.5m`, `19.4m`. Decimals aren't prone to scaling errors. Several databases (eg SQL Server) even prevent the number of decimals so that `10.50` remains `10.50` instead of becoming `10.5' – Panagiotis Kanavos Jun 18 '15 at 10:26
  • in order to print it accurate.you must round it using .ToString() method. `(eighteenPointFive + nineteenPointFour).ToString("R")` – M.kazem Akhgary Jun 18 '15 at 10:27
  • @M.kazemAkhgary ToString() doesn't round anything. Scaling errors have *already* occurred when adding. Besides, a string is useless for calculations – Panagiotis Kanavos Jun 18 '15 at 10:29

0 Answers0