0

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 ?

2 Answers2

1

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

Nathan
  • 553
  • 4
  • 11
1

Floating point numbers are often an approximation. There is a whole field of study about how to use floating numbers in a responsible way in computers and believe me, it is not trivial!
What most programmers do is live with it and make sure their code is 'robust' against the small deviations you get from using floating point numbers.
Wrong:

if (my_float== -0.01)


Right:

if (my_float>= -0.00999 && my_float<=-0.01001)

(The numbers are just as example).

If you need exact numbers you can e.g. use integers. You can use rounding but that is not done halfway calculations as you are likely to make the result more unreliable. Rounding is normally when you print the end result. After all as a good engineer you should know how many digits are relevant at the end.

Oldfart
  • 6,104
  • 2
  • 13
  • 15