Excel VBA四舍五入与 double

标签 excel floating-point double rounding-error vba

我正在尝试使用与我的工作表中的单元格相关的 double 来进行非常准确的计算。在测试时,我编写了以下代码:

Sub MacroTest()

Dim opt As Worksheet
Set opt = Sheets("Optimisation")

Dim test As Double

test = CDec(opt.Cells(2, 10))

End Sub

在单元格 J2 中是十进制值 - £3,298.8599993... 但是在调试代码时,很明显测试替身只选择 -3298.86 作为值。我不明白为什么会这样,因为我认为 double 比这更准确。我读过的大多数帖子似乎都认为使用 CDec 应该解决这个问题,但是如图所示,这似乎对我不起作用。

注意 - J2 中的值是使用公式计算的,不确定这是否有任何区别。非常感谢任何帮助 - 谢谢。

最佳答案

您应该使用 opt.Cells(2, 10).Value2在这种情况下。 Range.Value2 property :

The only difference between this property and the Value property is that the Value2 property doesn’t use the Currency and Date data types. You can return values formatted with these data types as floating-point numbers by using the Double data type.



所以默认.Value将返回 Currency如果单元格格式为货币,而 .Value2将返回 Double尽管如此。

关于Excel VBA四舍五入与 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38503339/

相关文章:

excel - 在 Excel 工作表之间粘贴时运行缓慢的宏和避免选择

lua - 有没有一种简单的方法来检查 2 个 float 是否近似相等?

Java parsefloat 在每个 CPU 上结果相同

java - java中的快速实值随机生成器

python - C 类型 float、double 和 long 的 Python 等价物是什么?

python - 使用 PySpark 读取 Excel 文件 : Failed to find data source: com. crealytics.spark.excel

excel - 计算机被锁定时如何发送电子邮件?

c++ - 从长位加倍

Python 将(读取和保存)excel xlsx 转换为 xls

python - 将两个原始值转换为 32 位 IEEE float