C# decimal multiplication strange behavior
c#, decimal, multiplication
Solution
`decimal` stores 28 or 29 significant digits (96 bits). Basically the mantissa is in the range -/+ 79,228,162,514,264,337,593,543,950,335.
That means up to about 7.9.... you can get 29 significant digits accurately - but above that you can't. That's why both the 8 and the 9 go wrong, but not the earlier values. You should only rely on 28 significant digits in general, to avoid odd situations like this.
Once you reduce your original input to 28 significant figures, you'll get the output you expect:
using System;
class Test
{
static void Main()
{
var input = 1.111111111111111111111111111m;
for (int i = 1; i < 10; i++)
{
decimal output = input * (decimal) i;
Console.WriteLine(output);
}
}
}
Problem
I noticed a strange behavior when multiplying decimal values in C#. Consider the following multiplication operations: ``` 1.1111111111111111111111111111m * 1m = 1.1111111111111111111111111111 // OK 1.1111111111111111111111111111m * 2m = 2.2222222222222222222222222222 // OK 1.1111111111111111111111111111m * 3m = 3.3333333333333333333333333333 // OK 1.1111111111111111111111111111m * 4m = 4.4444444444444444444444444444 // OK 1.1111111111111111111111111111m * 5m = 5.5555555555555555555555555555 // OK 1.1111111111111111111111111111m * 6m = 6.6666666666666666666666666666 // OK 1.1111111111111111111111111111m * 7m = 7.7777777777777777777777777777 // OK 1.1111111111111111111111111111m * 8m = 8.888888888888888888888888889 // Why not 8.8888888888888888888888888888 ? 1.1111111111111111111111111111m * 9m = 10.000000000000000000000000000 // Why not 9.9999999999999999999999999999 ? ``` What I cannot understand is the last two of above cases. How is that possible?