VBA四舍五入问题

编程入门 行业动态 更新时间:2024-10-23 13:33:35
本文介绍了VBA四舍五入问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我在VBA中有这个模糊的四舍五入问题。

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.

Link to paper

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四舍五入问题

本文发布于:2023-10-28 19:37:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1537587.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:四舍五入   VBA

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!