使用双打时的 .NET 问题
在 .NET 中,当我从 1.35072 中减去 1.35 时,它会显示 .000719999999。使用 double
时如何获得 .00072?
TOTKILO.Text = KILO.Text * TOUCH.Text * 0.01; //here 1.35072
TextBox10.Text = TextBox9.Text * TextBox8.Text * 0.01; //here 1.35
K = Val(TOTKILO.Text) - Val(TextBox10.Text); //here it shows 0.00719999
In .NET, when I subtract 1.35 from 1.35072 it shows .000719999999. How could I get .00072 when using a double
?
TOTKILO.Text = KILO.Text * TOUCH.Text * 0.01; //here 1.35072
TextBox10.Text = TextBox9.Text * TextBox8.Text * 0.01; //here 1.35
K = Val(TOTKILO.Text) - Val(TextBox10.Text); //here it shows 0.00719999
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
双精度数和浮点数的表示精度始终与我们想象的不同。始终将值四舍五入到小数点后几位,然后检查答案。
其他详细信息请参见如何解决浮点精度/比较问题 >。
Doubles and floating points are always represented with a varying degree of precision than what we visualize them to be. Always round up the values to few decimals and then check the answers.
Additional details are in How To Work Around Floating-Point Accuracy/Comparison Problems.
取决于你真正要问的是什么。
如果您想四舍五入到小数点后五位,您可以这样做:
另一方面,如果您的目标是始终通过添加/减去小数来获得精确的结果,请使用
decimal
类型而不是double
因为它本质上是一个以 10 为基数的类型(而不是以 2 为基数的类型),因此可以精确地表示以十进制形式表示的数字。Depends on what you're really asking.
If you want to round to five decimal places, you can just do:
If, on the other hand, your goal is to always get precise results from adding/subtracting decimal numbers, use the
decimal
type instead ofdouble
since it is inherently a base-10 type (as opposed to a base-2 type) and can therefore represent numbers expressed in decimal form precisely.据我所知,您几乎从来不需要
double
。几乎所有时候,decimal
(System.Decimal
) 都能满足您的需要,而且它是一个精确的数字,而不是浮点表示形式,因此您永远不会有这些舍入问题。From what I've seen, you almost never actually need a
double
. Nearly all the time adecimal
(System.Decimal
) works for what you need, and it is an exact number, not a floating point representation, so you'll never have these rounding problems.