VBA四舍五入问题 [英] VBA rounding problem
问题描述
a = 61048.4599674847
b = 154553063.208822
c = a + b
debug.print c
结果:
154614111.66879
这是一个问题,为什么VBA取整了变量C?我没有发出任何四舍五入的功能。我期待的价值是154614111.6687894847。即使我舍弃或将变量C格式化为15位小数,我仍然没有得到我的预期结果。
任何解释都将不胜感激。
编辑:
使用cDec获得预期结果。我已经在Jonathan Allen的为什么会产生不同结果的回复中已经看过这篇文章?
以下是测试结果:
a = cDec(61048.4599674847)$ b $
$ =h2_lin>解决方案
原因是可以存储在浮点变量中的限制条件。
有关完整说明,请参阅论文每个计算机科学家应该了解浮点数算法,由David Goldberg在1991年3月发行的计算机调查中发表。
在VBA中,默认浮点类型为 Double
,它是IEEE 64位(8字节)浮点数。 / p>
还有另一种类型可用:十进制
这是一个96位(12字节)可变功率为10
简单来说,这将提供浮点数到28位数字。
要在您的示例中使用:
a = CDec(61048.4599674847)
b = CDec(154553063.208822)
c = a + b
debug.print c
结果:
154614111.6687894847
I have this obscure rounding problem in VBA.
a = 61048.4599674847
b = 154553063.208822
c = a + b
debug.print c
Result:
154614111.66879
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.
Any explanation would be appreciated.
Edit:
Got the expected results using cDec. I have read this in Jonathan Allen's reply in Why does CLng produce different results?
Here is the result to the test:
a = cDec(61048.4599674847)
b = cDec(154553063.208822)
c = a + b
?c
154614111.6687894847
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.
In VBA the default floating point type is Double
which is a IEEE 64-bit (8-byte) floating-point number.
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.
To use in your example:
a = CDec(61048.4599674847)
b = CDec(154553063.208822)
c = a + b
debug.print c
Result:
154614111.6687894847
这篇关于VBA四舍五入问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!