C# wrong subtraction? 12.345 - 12 = 0.34500000000

2019-04-20 19:30发布

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.

5条回答
我欲成王,谁敢阻挡
2楼-- · 2019-04-20 19:44

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

查看更多
啃猪蹄的小仙女
3楼-- · 2019-04-20 19:47

Depending in what you you can use either decimal type, or store it as is, but round before displaying the answer

查看更多
Deceive 欺骗
4楼-- · 2019-04-20 19:52

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

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

查看更多
姐就是有狂的资本
5楼-- · 2019-04-20 20:03

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

查看更多
疯言疯语
6楼-- · 2019-04-20 20:04

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.

查看更多
登录 后发表回答