Search code examples
numberssubtraction

Result of Subtraction Two Float number C#


Consider two number like 1 and 0.99 and i want to sub these number in C#

float s = 0.99f - 1f;
Console.WriteLine(s.toString());
result is : -0.0099999

what can i do that result equal to -0.01 ?


Solution

  • Try this;

    decimal d = 0.99m - 1m;
    Console.WriteLine(Math.Round(d, 2));
    

    Computers aren't able to perfectly represent fractional numbers. They can only approximate them which is why you're seeing -0.0099999 instead of the expected -0.01.

    For anything that you require close approximations you'd typically use an arbitrary precision type and round where appropriate. The most common rounding for currency is bankers rounding as it doesn't skew results heavily in either direction.

    See also:

    What is the best data type to use for money in c#?

    http://wiki.c2.com/?BankersRounding