为什么在VBA访问134.605 * 100不等于13460.5? [英] Why is 134.605*100 not equal 13460.5 in VBA Access?
问题描述
我想这事做的precision,但我不明白。我有这块code,应该进行舍入到2位(值的是输入):
I guess it has something to do with the precision but I don't understand it. I have this piece of code that should perform rounding to 2 places (value is the input):
Dim a As Double
Dim b As Double
Dim c As Double
Dim result As Double
a = CDbl(value) * 100
b = a + 0.5 //because Int in the next line performs floor operation, 0.5 is added to ensure proper rounding, example for 123.5: Int(123.5) = 123 but we need Int(123.5 + 0.5) = 124
c = Int(b)
result = c / 100
的事情是,它不正确的值134.605的工作。在调试我发现,一个值计算不正确。 其实我已经检查了这一点:
The thing is, it doesn't work properly for a value 134.605. While debugging I found out that a value is calculated incorrectly. In fact I have checked this:
?13460.5 = (134.605*100)
False
?(134.605*100) - 13460.5
-1,02318153949454E-12
和我被困。我可以重写四舍五入的功能有所不同,但我不无* 100乘有一个想法吧。或者,我可以找出如何使* 100的操作正确地工作,为所有的值。任何人都可以尝试,为什么它发生在我解释,并提出一个解决方案?
And I'm stuck. I can either rewrite the rounding function differently, but I don't have an idea for it without *100 multiplication. Or I could find out how to make *100 operation work correctly for all the values. Could anyone try to explain me why it happens and suggest a solution?
推荐答案
尝试十进制
的数据类型。虽然不能明确地声明这种类型的变量,你可以含蓄地声明为变式
并使用转换 CDEC $ C将其转换为这样的$ C>。
Try Decimal
data type. Although you cannot explicitly declare a variable of this type, you can convert it to such implicitly by declaring it as Variant
and converting using CDec
.
Debug.Print 13460.5 = CDec(134.605 * 100) 'Output - True
这篇关于为什么在VBA访问134.605 * 100不等于13460.5?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!