使用CType与VB.net单一返回额外的数字

时间:2014-01-14 19:38:38

标签: vb.net

我正在使用VB.NET 2010.我遇到了一个问题,起初我认为是数据库问题,因为值是从DB2表中提取的。但是,它似乎是在.NET本身。我通过运行以下两行代码确定了这一点:

    Dim sAmount As Single
    sAmount = CType("212639.04", Single)

当我查看sAmount时,值为212639.047。

我的问题:7来自哪里?

1 个答案:

答案 0 :(得分:2)

麻烦的是你正在使用Single这是一种浮动数据类型,它不适用于非二进制分数的分数。

Floating-Point Expressions Do Not Compare as Equal

  

使用浮点数时(单数据类型(Visual   基本)和双数据类型(Visual Basic)),记住它们是   存储为二进制分数。这意味着他们无法保持准确   表示任何不是二进制分数的数量   形式k /(2 ^ n)其中k和n是整数)。例如,0.5(= 1/2)   和0.3125(= 5/16)可以保持为精确值,而0.2(= 1/5)   和0.3(= 3/10)只能是近似值。

     

由于这种不精确,你不能依赖于确切的结果   对浮点值进行操作。特别是,两个值是   在理论上相等可能会有略微不同的表示。

     

比较浮点数量

Calculate the absolute value of their difference by using the Abs method of the 
Math class in the System namespace.

Determine an acceptable maximum difference, such that you can consider the two 
quantities to be equal for practical purposes if their difference is no larger.

Compare the absolute value of the difference to the acceptable difference.

或者,double将返回一个更精确的数字。