C# wrong subtraction? 12.345 - 12 = 0.345000000000001

c0ntrol picture c0ntrol · Mar 27, 2012 · Viewed 16.7k times · Source

I am beginner in C# and I am working with floating point numbers. I need to do subtraction between these two numbers but it does not work. I know it is caused by floating point number, but how can I fix it please and if you be so good can you explain me why is it happening? Thanks in advance.

Answer

Hector Correa picture Hector Correa · Mar 27, 2012

Consider using decimal instead of float:

// Instead of this...
float a = 12.345F;
float b = 12;
float c = a - b;

// Use this: 
decimal d = 12.345M;
decimal e = 12;
decimal f = d - e;

Jon Skeet gives a good explanation of the differences between both types in this answer: https://stackoverflow.com/a/618596/446681