VBA终极四舍五入

时间:2013-08-27 07:44:22

标签: excel vba math excel-vba

我已经阅读了很多关于在Excel中进行舍入的内容。我发现VBA的Round()函数使用“Bankers rounding”,而Application.WorksheetFunction.Round()使用或多或少的“正常”舍入。但这并没有帮助我理解这一点:

? Round(6.03499,2)
 6.03 

为什么呢?我想看6.04,而不是6.03!诀窍是

? Round(Round(6.03499,3),2)
 6.04

我想了一下并开发了这样一个子程序:

Option Explicit
Function DoRound(ByVal value As Double, Optional ByVal numdigits As Integer = 0) As Double
   Dim i As Integer
   Dim res As Double
   res = value
   For i = 10 To numdigits Step -1
       res = Application.Round(res, i)
   Next i
   DoRound = res
End Function

工作正常。

? DoRound(6.03499,2)
  6.04

但这并不酷。在Excel中是否有任何内置的普通舍入?

2 个答案:

答案 0 :(得分:3)

如果您将6.03499舍入为3位数,则为6.035 - 这是正确的 如果您将6.03499舍入为2位数,则为6.03 - 这是正确的

但是 - 您首先舍入到3位数,然后到2位的示例也是正确的,通过以下语句:
Round(6.03499, 3)给出6.035
Round(6.035, 2)给出6.04

如果您希望Round(6.03499, 2)提供6.04,则必须使用Application.WorksheetFunction.RoundUp

答案 1 :(得分:1)

舍入6.0349到两位小数不是6.04因此,不,没有这样的功能。 回合将围绕任何事情。因此,如果您舍入到0小数,则6.0000000001也将变为7。