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.
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
remember that the behavior of floating points can vary depending on the processor you are using.
Here is an question on this forum that deals with the subject
If you really want to dig into the subject, here is a good source on how to examine the behavior of floating-point
Depending in what you you can use either decimal type, or store it as is, but round before displaying the answer
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.
Float C# reference
Double C# reference
Consider using decimal instead of float:
Jon Skeet gives a good explanation of the differences between both types in this answer: https://stackoverflow.com/a/618596/446681
How exactly are you calculating?
For me these calculations give the correct results.