使用双打时的 .NET 问题

发布于 2024-10-20 13:10:22 字数 324 浏览 6 评论 0原文

在 .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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

少女情怀诗 2024-10-27 13:10:23

双精度数和浮点数的表示精度始终与我们想象的不同。始终将值四舍五入到小数点后几位,然后检查答案。

其他详细信息请参见如何解决浮点精度/比较问题 >。

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.

韶华倾负 2024-10-27 13:10:22

取决于你真正要问的是什么。

如果您想四舍五入到小数点后五位,您可以这样做:

double x = 1.35072;
double y = 1.35;
double z = Math.Round(x - y, 5); // 0.00072

另一方面,如果您的目标是始终通过添加/减去小数来获得精确的结果,请使用 decimal 类型而不是double 因为它本质上是一个以 10 为基数的类型(而不是以 2 为基数的类型),因此可以精确地表示以十进制形式表示的数字。

decimal x = 1.35072M;
decimal y = 1.35M;
decimal z = x - y; // 0.00072M

Depends on what you're really asking.

If you want to round to five decimal places, you can just do:

double x = 1.35072;
double y = 1.35;
double z = Math.Round(x - y, 5); // 0.00072

If, on the other hand, your goal is to always get precise results from adding/subtracting decimal numbers, use the decimal type instead of double 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.

decimal x = 1.35072M;
decimal y = 1.35M;
decimal z = x - y; // 0.00072M
゛清羽墨安 2024-10-27 13:10:22

据我所知,您几乎从来不需要double。几乎所有时候,decimal (System.Decimal) 都能满足您的需要,而且它是一个精确的数字,而不是浮点表示形式,因此您永远不会有这些舍入问题。

From what I've seen, you almost never actually need a double. Nearly all the time a decimal (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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文