vb.net - 使用 CType 与 VB.net 单选返回额外的数字

标签 vb.net

我正在使用 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/

相关文章:

c# - 按字母顺序和类型对列表进行排序

c# - 自定义 HTTP 错误页面

vb.net - 返回在 vb.net 中获取 datagridview 单元格值

mysql - 使用.NET执行MySQL的SQL文件

sql - 关于 SQL 语句的语法,我错过了什么?

regex - 从字符串中分离字符和数字,vb.net

c# - 声明成员变量并初始化而不重复类型

vb.net - 隐式创建的Form是如何工作的?

c# - C# 比 VB.NET 快吗?

vb.net - 如何从 vb.net 应用程序运行 Windows 命令 "mklink"?