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.
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
This is not a c# problem, this is a computer science problem. If you want to truly understand what is going on, read What Every Computer Scientist Should Know About Floating-Point Arithmetic. If you just care about why you're having the problem, it's because Float and Double are only precise to 7 and 15 digits respectively on this platform, and you need to apply rounding logic to achieve the result you are looking for.
Squeezing infinitely many real numbers into a finite number of bits requires an approximate representation. Although there are infinitely many integers, in most programs the result of integer computations can be stored in 32 bits. In contrast, given any fixed number of bits, most calculations with real numbers will produce quantities that cannot be exactly represented using that many bits. Therefore the result of a floating-point calculation must often be rounded in order to fit back into its finite representation. This rounding error is the characteristic feature of floating-point computation. Goldberg 1991
How exactly are you calculating?
float a = 12.35F;
float b = 12.0F;
float ans = a - b; //0.350000381
double x = 12.35;
double y = 12.0;
double ans2 = x - y; //0.34999999999999964
decimal n = 12.35m;
decimal m = 12.0m;
decimal ans3 = n - m; //0.35
For me these calculations give the correct results.
Depending in what you you can use either decimal type, or store it as is, but round before displaying the answer
来源:https://stackoverflow.com/questions/9890477/c-sharp-wrong-subtraction-12-345-12-0-345000000000001