C#浮动神奇地改变价值 [英] C# float magically changing value

查看:64
本文介绍了C#浮动神奇地改变价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我的浮动货币持有一个非常重要的值,必须非常准确.
我遇到的问题是我只更改浮点数的值,总是+和-(此处无除法).
更改该值约20次后,该值不符合预期的0.05,即0.0499989.
为什么呢?我没有强制转换浮点数,也没有将其分开,但是它神奇地从0.05更改为0.049989.
我尝试了Math.Round(value, 2);,但是它也不返回0.05.我现在该怎么办?


I have a float holding a very important value, which has to be VERY exact.
The problem I have is I'm changing the value of the float ALWAYS only + and - (No division here).
After changing the value about 20 times, the value isn't 0.05 as expected, its 0.0499989.
Why is this? Im not casting the float, I'm not dviding it, but it magically changes from 0.05 to 0.049989.
I tried Math.Round(value, 2); but it doesn't return 0.05 either. What should I do now??

推荐答案

许多(如果不是大多数)语言中的浮点变量仅持有实际值的不精确近似值.您可以使用decimal数据类型解决C#中的问题. 请参阅此SO问题.

Floating point variables in many (if not most) languages only hold an imprecise approximation of the actual value. You can solve the issue in C# by using the decimal data type. See this SO question.

这篇关于C#浮动神奇地改变价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆