Convert.ToDouble问题 [英] Issue with Convert.ToDouble

查看:207
本文介绍了Convert.ToDouble问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码进行数学运算



Convert.ToDouble(80.1)* 100000.0



我应该得到的答案是8010000(入住计算器)。但上面给我的asnwer是8009999.9999999991。任何人都可以告诉我为什么会发生这种情况以及进行数学运算的正确方法是什么?

I used the below code for a math operation

Convert.ToDouble("80.1") * 100000.0

The answer i was supposed to get is 8010000 (Check in calculator). But the asnwer the above line gave me was 8009999.9999999991. Can anyone please tell me why this is happening and what is the correct way to do this math operation?

推荐答案

没有问题。这是预期的,因为您的计算机无法准确表示所有浮点数。见这里:

http://effbot.org /pyfaq/why-are-floating-point-calculations-so-inaccurate.htm [ ^ ]



和这里:

< a href =http://stackoverflow.com/questions/2100490/floating-point-inaccuracy-examples> http://stackoverflow.com/questions/2100490/floating-point-inaccuracy-examples [< a href =http://stackoverflow.com/questions/2100490/floating-point-inaccuracy-examplestarget =_ blanktitle =New Window> ^ ]



如果你想在这里继续前进:

http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html [ ^ ]



您可以在此主题上找到许多其他链接,包括:

浮点编程的五个提示 [ ^ ]



如果你戳得更深,你会发现100000.0可以是完全代表,但80.1不能是80.099999999999994。乘法的确切结果也可能无法准确表示,因此我们可以了解您的情况。



您可能还希望查看具有的十进制类型在较小范围内具有更高的精度。这尤其适用于货币价值。

https://msdn.microsoft.com /en-us/library/364x0z75.aspx [ ^ ]
There is no issue. This is expected as your computer cannot exactly represent all floating point numbers. See here:
http://effbot.org/pyfaq/why-are-floating-point-calculations-so-inaccurate.htm[^]

and here:
http://stackoverflow.com/questions/2100490/floating-point-inaccuracy-examples[^]

and if you wish to go further here:
http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html[^]

There are many other links you can find on this subject including this:
Five Tips for Floating Point Programming[^]

If you poke a little deeper you will find 100000.0 can be represented exactly but 80.1 cannot being 80.099999999999994. The exact result of the multiplication may also not be able to be represented exactly so we get to your situation.

You may also wish to look at the decimal type which has greater precision over a smaller range. This particularly applies to money values.
https://msdn.microsoft.com/en-us/library/364x0z75.aspx[^]


你可以使用math.Round方法获得预期的输出
you can use math.Round method for getting the expected output


感谢回复人员。就像在链接中提到的那样,我的计算机可能存在正确表示浮点的问题。



使用Convert.ToDecimal(80.1)* Parse.Decimal(100000.0)给出了确切的结果。
Thanks for the reply guys. Like mentioned in the link my computer might be having issues representing floating point correctly.

Using Convert.ToDecimal("80.1") * Parse.Decimal("100000.0") gives me the exact result.


这篇关于Convert.ToDouble问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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