VBA 舍入问题 [英] VBA rounding problem
问题描述
我在 VBA 中有这个晦涩的舍入问题.
I have this obscure rounding problem in VBA.
a = 61048.4599674847
b = 154553063.208822
c = a + b
debug.print c
Result:
154614111.66879
问题来了,为什么 VBA 将变量 c 舍入?我没有发出任何舍入功能.我期望的值是 154614111.6687894847.即使我四舍五入或将变量 c 格式化为小数点后 15 位,我仍然没有得到预期的结果.
Here is the question, why did VBA rounded off variable c? I didn't issued any rounding off function. The value I was expecting was 154614111.6687894847. Even if I round off or format variable c to 15 decimal places I still don't get my expected result.
任何解释将不胜感激.
使用 cDec 获得了预期的结果.我在 Jonathan Allen 在 为什么 CLng 产生不同的结果?
Got the expected results using cDec. I have read this in Jonathan Allen's reply in Why does CLng produce different results?
测试结果如下:
a = cDec(61048.4599674847)
b = cDec(154553063.208822)
c = a + b
?c
154614111.6687894847
推荐答案
原因是可以存储在浮点变量中的精度有限.
要获得完整的解释,您应该阅读 David Goldberg 于 1991 年 3 月出版的 Computing Surveys 论文What Every Computer Scientist should Know About Floating-Point Arithmetic.
The reason is the limited precission that can be stored in a floating point variable.
For a complete explanation you shoud read the paper What Every Computer Scientist Should Know About Floating-Point Arithmetic, by David Goldberg, published in the March, 1991 issue of Computing Surveys.
在 VBA 中,默认浮点类型是 Double
,这是一个 IEEE 64 位(8 字节)浮点数.
In VBA the default floating point type is Double
which is a IEEE 64-bit (8-byte) floating-point number.
还有另一种类型:Decimal
,它是一个 96 位(12 字节)有符号整数,按 10 的可变幂进行缩放
简而言之,这提供了 28 位精度的浮点数.
There is another type available: Decimal
which is a 96-bit (12-byte) signed integers scaled by a variable power of 10
Put simply, this provides floating point numbers to 28 digit precission.
在您的示例中使用:
a = CDec(61048.4599674847)
b = CDec(154553063.208822)
c = a + b
debug.print c
Result:
154614111.6687894847
这篇关于VBA 舍入问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!