-2

In C#

(18761311001m * 0.36m + 
 18761311001m * 0.35m +
 18761311001m * 0.29m) 
/66.1445m 
=   283641285.38276047139217924393

But

((18761311001m * 0.36m)/66.1445m) + 
((18761311001m * 0.35m)/66.1445m) + 
((18761311001m * 0.29m) /66.1445m) 
= 283641285.38276047139217924392

Anyone know why the difference and how to get the same answer for both?

Thanks

  • 1
    Possible duplicate of [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Liam Nov 19 '15 at 12:15
  • Also [Why is floating point arithmetic in C# imprecise?](http://stackoverflow.com/questions/753948/why-is-floating-point-arithmetic-in-c-sharp-imprecise) – Liam Nov 19 '15 at 12:15
  • 1
    What is your application doing where a sextillionth will make a difference? – Atron Seige Nov 19 '15 at 12:18
  • 2
    This is not a duplicate of the floating point math, since this is about *decimals*. The `decimal` type is not an IEEE 754 type. But there is surely a good duplicate somewhere. – poke Nov 19 '15 at 12:18
  • @poke, IEEE754 has got decimal types, although the Microsoft implementation does not conform. But of course, the principle behind the OPs problem is exactly the same. – Adrian Ratnapala Nov 19 '15 at 12:20
  • @Atron Seige Won't make a difference so have now rounded the number to 20 (unit test) – user99995454 Nov 19 '15 at 12:33
  • While this isn't about floating point it is similar. Due to finite precision there will be rounding errors in intermediate results. Different operation will lead to different errors. So the results are – as with floating point – affected by the order of operations. Summary: finite representation has rounding errors. – Richard Nov 19 '15 at 13:20

1 Answers1

2

decimal has 28 significant digits. Your difference is at the 29th digit.

If you need more precision, you'll have to use an arbitrary-precision math library. See this answer for some suggestions.

Community
  • 1
  • 1
Lucas Trzesniewski
  • 50,214
  • 11
  • 107
  • 158