我正在使用 VB.NET 2010。我遇到了一个问题,起初我认为是数据库问题,因为该值是从 DB2 表中提取的。但是,它似乎在 .NET 中。我通过运行以下两行代码来确定这一点:
Dim sAmount As Single
sAmount = CType("212639.04", Single)
当我查看 sAmount 时,该值为 212639.047。
我的问题: 7 来自哪里?
最佳答案
问题是您使用的是 Single ,它是一种浮点数据类型,它不适用于不是二进制分数的分数。
Floating-Point Expressions Do Not Compare as Equal
When you work with floating-point numbers (Single Data Type (Visual Basic) and Double Data Type (Visual Basic)), remember that they are stored as binary fractions. This means they cannot hold an exact representation of any quantity that is not a binary fraction (of the form k / (2 ^ n) where k and n are integers). For example, 0.5 (= 1/2) and 0.3125 (= 5/16) can be held as precise values, whereas 0.2 (= 1/5) and 0.3 (= 3/10) can be only approximations.
Because of this imprecision, you cannot rely on exact results when you operate on floating-point values. In particular, two values that are theoretically equal might have slightly different representations.
To compare floating-point quantities
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 将返回一个更精确的数字。
关于vb.net - 使用 CType 与 VB.net 单选返回额外的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21122441/