0

I am getting different results for the double and decimal calculations...

double value1 = 280.585 - 280.50;
decimal value2 = Convert.ToDecimal(280.585) - Convert.ToDecimal(280.50);
Console.WriteLine(value1);
Console.WriteLine(value2);

Output:

Double:0.0849999999999795
Decimal:0.085

But how come int and long give the same results?

int value1 =  2+2;
long value2 = 2+2;
Console.WriteLine(value1);
Console.WriteLine(value2);

Output:

4
4
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 2
    Because `int` (`System.Int32`) and `long` (`System.Int64`) are both integer types. And `long` has just more bytes to represent an integer value than `int` does. `Double` and `decimal` are fundamentally different ways to represent numbers. And `double` is not a "bigger version" of `decimal` (or vice versa). The Link @John posted discusses the difference. Basically a `decimal` is a bit like an integer value with a decimal separator somewhere, while a `double` is "more complicated" with sign, exponent and mantissa. https://blogs.msdn.microsoft.com/ericlippert/2011/02/17/looking-inside-a-double/ – Corak Oct 09 '19 at 06:37

1 Answers1

2

280.585 and 280.5 are both exactly representable as short decimal fractions, as is their difference.

Assuming double is represented as IEEE 754 64-bit binary floating point, the closest double to 280.585 is 280.58499999999997953636921010911464691162109375. 280.5 is exactly representable as a double. Their difference is 0.08499999999997953636921010911464691162109375.

In the case of the 2+2=4 calculation, all the numbers are exactly representable in either int or long so both should get the exact answer.

Patricia Shanahan
  • 25,849
  • 4
  • 38
  • 75