我有以下数据:
cell(1,1) = 2878.75
cell(1,2) = $31.10
cell(2,1) = $89,529.13
然而,当我尝试使用round(cells(1,1).value*cells(1,2).value),2)
时,结果与cell(2,1)
不匹配。我想这可能与四舍五入问题有关,但我只是想知道是否有可能让round()
正常工作。也就是说,对于value > 0.5
,向上取整。对于value < 0.5
,向下取整?
VBA使用银行家舍入法试图弥补总是四舍五入的偏差; 您可以选择。
WorksheetFunction.Round(cells(1,1).value * cells(1,2).value, 2)
如果你想进行四舍五入,可以使用半调整法。将0.5加到需要进行四舍五入的数字上并使用INT()函数。
答案 = INT(x + 0.5)
Round(41.0 + 0.5)
的结果将为 42
。 - MCLInt(x + 0.49)
怎么样? @Ans:chaaaa :-D - gaffcz
试试这个函数,可以将一个double值向上取整
'---------------Start -------------
Function Round_Up(ByVal d As Double) As Integer
Dim result As Integer
result = Math.Round(d)
If result >= d Then
Round_Up = result
Else
Round_Up = result + 1
End If
End Function
'-----------------End----------------
尝试使用RoundUp函数:
Dim i As Double
i = Application.WorksheetFunction.RoundUp(Cells(1, 1).Value * Cells(1, 2).Value, 2)
我介绍了两个定制的库函数,可用于VBA,其目的是将双倍值四舍五入,而不是使用WorkSheetFunction.RoundDown和WorkSheetFunction.RoundUp。
Function RDown(Amount As Double, digits As Integer) As Double
RDown = Int((Amount + (1 / (10 ^ (digits + 1)))) * (10 ^ digits)) / (10 ^ digits)
End Function
Function RUp(Amount As Double, digits As Integer) As Double
RUp = RDown(Amount + (5 / (10 ^ (digits + 1))), digits)
End Function
因此,函数Rdown(2878.75 * 31.1,2)将返回899529.12, 而函数RUp(2878.75 * 31.1,2)将返回899529.13。 然而,函数Rdown(2878.75 * 31.1,-3)将返回89000, 而函数RUp(2878.75 * 31.1,-3)将返回90000。
我遇到了一个问题,需要进行向上取整,但是这些答案并不能满足我的代码运行要求,所以我使用了不同的方法。 INT函数会向负数方向舍入(4.2变为4,-4.2变为-5) 因此,我将我的函数更改为负数,应用INT函数,然后通过在前后乘以-1来将其返回为正数。
Count = -1 * (int(-1 * x))
Function RoundUpVBA(InputDbl As Double, Digits As Integer) As Double
If InputDbl >= O Then
If InputDbl = Round(InputDbl, Digits) Then RoundUpVBA = InputDbl Else RoundUpVBA = Round(InputDbl + 0.5 / (10 ^ Digits), Digits)
Else
If InputDbl = Round(InputDbl, Digits) Then RoundUpVBA = InputDbl Else RoundUpVBA = Round(InputDbl - 0.5 / (10 ^ Digits), Digits)
End If
End Function
或者:
Function RoundUpToWhole(InputDbl As Double) As Integer
Dim TruncatedDbl As Double
TruncatedDbl = Fix(InputDbl)
If TruncatedDbl <> InputDbl Then
If TruncatedDbl >= 0 Then RoundUpToWhole = TruncatedDbl + 1 Else RoundUpToWhole = TruncatedDbl - 1
Else
RoundUpToWhole = TruncatedDbl
End If
End Function
以上一些答案涵盖了相似的领域,但这里是独立自足的。我也在我的其他答案中讨论了一些一行代码的快捷方式来进行四舍五入。
这对我有用
Function round_Up_To_Int(n As Double)
If Math.Round(n) = n Or Math.Round(n) = 0 Then
round_Up_To_Int = Math.Round(n)
Else: round_Up_To_Int = Math.Round(n + 0.5)
End If
End Function
Math.Round使用银行家舍入法,如果要舍入的数字恰好处于中间位置,它会舍入到最接近的偶数。
简单解决方案是使用Worksheetfunction.Round()。这将在边缘情况下向上舍入。
这是一个例子,j 是你想要向上取整的值。
Dim i As Integer
Dim ii, j As Double
j = 27.11
i = (j) ' i is an integer and truncates the decimal
ii = (j) ' ii retains the decimal
If ii - i > 0 Then i = i + 1
如果余数大于0,则将其四舍五入,简单明了。在1.5时,它会自动四舍五入为2,因此余数小于0。
Round
函数就是这样运作的。问题在于当value=0.5
时它会怎么处理。 - Doc Brown