将数字四舍五入到最接近的 5 或 10 或 X

发布于 2024-07-08 22:31:10 字数 251 浏览 7 评论 0原文

给定数字如 499、73433、2348,我可以使用什么 VBA 来四舍五入到最接近的 5 或 10? 或任意数字?

5:

 499 ->  500
2348 -> 2350
7343 -> 7345

10:

 499 ->  500
2348 -> 2350
7343 -> 7340

Given numbers like 499, 73433, 2348 what VBA can I use to round to the nearest 5 or 10? or an arbitrary number?

By 5:

 499 ->  500
2348 -> 2350
7343 -> 7345

By 10:

 499 ->  500
2348 -> 2350
7343 -> 7340

etc.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

窝囊感情。 2024-07-15 22:31:11

对于严格的 Visual Basic 方法,您可以将浮点值转换为整数,以四舍五入为所述整数。 VB 是在类型转换上进行舍入的罕见语言之一(大多数其他语言只是截断)。5

或 x 的倍数可以简单地通过在舍入之前除法和在舍入之后相乘来完成。

如果你想四舍五入并保留小数位,Math.round(n, d) 就可以了。

For a strict Visual Basic approach, you can convert the floating-point value to an integer to round to said integer. VB is one of the rare languages that rounds on type conversion (most others simply truncate.)

Multiples of 5 or x can be done simply by dividing before and multiplying after the round.

If you want to round and keep decimal places, Math.round(n, d) would work.

娇纵 2024-07-15 22:31:11

这是我们的解决方案:

Public Enum RoundingDirection
    Nearest
    Up
    Down
End Enum

Public Shared Function GetRoundedNumber(ByVal number As Decimal, ByVal multiplier As Decimal, ByVal direction As RoundingDirection) As Decimal
    Dim nearestValue As Decimal = (CInt(number / multiplier) * multiplier)
    Select Case direction
        Case RoundingDirection.Nearest
            Return nearestValue
        Case RoundingDirection.Up
            If nearestValue >= number Then
                Return nearestValue
            Else
                Return nearestValue + multiplier
            End If
        Case RoundingDirection.Down
            If nearestValue <= number Then
                Return nearestValue
            Else
                Return nearestValue - multiplier
            End If
    End Select
End Function

用法:

dim decTotal as Decimal = GetRoundedNumber(CDec(499), CDec(0.05), RoundingDirection.Up)

Here is our solution:

Public Enum RoundingDirection
    Nearest
    Up
    Down
End Enum

Public Shared Function GetRoundedNumber(ByVal number As Decimal, ByVal multiplier As Decimal, ByVal direction As RoundingDirection) As Decimal
    Dim nearestValue As Decimal = (CInt(number / multiplier) * multiplier)
    Select Case direction
        Case RoundingDirection.Nearest
            Return nearestValue
        Case RoundingDirection.Up
            If nearestValue >= number Then
                Return nearestValue
            Else
                Return nearestValue + multiplier
            End If
        Case RoundingDirection.Down
            If nearestValue <= number Then
                Return nearestValue
            Else
                Return nearestValue - multiplier
            End If
    End Select
End Function

Usage:

dim decTotal as Decimal = GetRoundedNumber(CDec(499), CDec(0.05), RoundingDirection.Up)
迟月 2024-07-15 22:31:11

只需 ROUND(x/5)*5 就可以完成这项工作。

Simply ROUND(x/5)*5 should do the job.

孤星 2024-07-15 22:31:11

我无法添加评论,所以我将在 vbs 运行中使用它

,并有趣地弄清楚为什么 2 给出的结果是 2

你不能信任回合

 msgbox round(1.5) 'result to 2
 msgbox round(2.5) 'yes, result to 2 too

I cannot add comment so I will use this

in a vbs run that and have fun figuring out why the 2 give a result of 2

you can't trust round

 msgbox round(1.5) 'result to 2
 msgbox round(2.5) 'yes, result to 2 too
眼趣 2024-07-15 22:31:11

类似的东西?

'nearest
 n = 5
 'n = 10

 'value
 v = 496
 'v = 499 
 'v = 2348 
 'v = 7343

 'mod
 m = (v \ n) * n

 'diff between mod and the val
 i = v-m


 if i >= (n/2) then     
      msgbox m+n
 else
      msgbox m
 end if

something like that?

'nearest
 n = 5
 'n = 10

 'value
 v = 496
 'v = 499 
 'v = 2348 
 'v = 7343

 'mod
 m = (v \ n) * n

 'diff between mod and the val
 i = v-m


 if i >= (n/2) then     
      msgbox m+n
 else
      msgbox m
 end if
玩心态 2024-07-15 22:31:11

试试这个功能

--------------开始----------------

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

-------------结束-- ----------

Try this function

--------------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 ------------

秉烛思 2024-07-15 22:31:11

我稍微更新了“社区维基”(最佳答案)提供的函数,只是四舍五入到最接近的 5(或任何你喜欢的值),但有一个例外:四舍五入的数字永远不会优于原始数字

当需要说“一家公司已存在 47 年”时,这非常有用:我希望网页显示“已存在超过 45 年” strong>,同时避免撒谎说“已经活了 50 多年”

因此,当您向此函数输入 47 时,它不会返回 50,而是返回 45。

'Rounds a number to the nearest unit, never exceeding the actual value
function RoundToNearestOrBelow(num, r)

    '@param         num         Long/Integer/Double     The number to be rounded
    '@param         r           Long                    The rounding value
    '@return        OUT         Long                    The rounded value

    'Example usage :
    '   Round 47 to the nearest 5 : it will return 45
    '   Response.Write RoundToNearestBelow(47, 5)

    Dim OUT : OUT = num

    Dim rounded : rounded = Round((((num)) / r), 0) * r

    if (rounded =< num) then
        OUT = rounded
    else
        OUT = rounded - r
    end if

    'Return
    RoundToNearestOrBelow = OUT

end function 'RoundToNearestOrBelow

I slightly updated the function provided by the "community wiki" (the best answer), just to round to the nearest 5 (or anything you like), with this exception : the rounded number will NEVER be superior to the original number.

This is useful in cases when it is needed to say that "a company is alive for 47 years" : I want the web page to display "is alive for more than 45 years", while avoiding lying in stating "is alive for more than 50 years".

So when you feed this function with 47, it will not return 50, but will return 45 instead.

'Rounds a number to the nearest unit, never exceeding the actual value
function RoundToNearestOrBelow(num, r)

    '@param         num         Long/Integer/Double     The number to be rounded
    '@param         r           Long                    The rounding value
    '@return        OUT         Long                    The rounded value

    'Example usage :
    '   Round 47 to the nearest 5 : it will return 45
    '   Response.Write RoundToNearestBelow(47, 5)

    Dim OUT : OUT = num

    Dim rounded : rounded = Round((((num)) / r), 0) * r

    if (rounded =< num) then
        OUT = rounded
    else
        OUT = rounded - r
    end if

    'Return
    RoundToNearestOrBelow = OUT

end function 'RoundToNearestOrBelow
烟织青萝梦 2024-07-15 22:31:11

要在 Visual Basic 中模仿舍入函数在 Excel 中的工作方式,您只需使用:
WorksheetFunction.Round(number,decimals)

这样银行或会计舍入就不会进行舍入。

To mimic in Visual Basic the way the round function works in Excel, you just have to use:
WorksheetFunction.Round(number, decimals)

This way the banking or accounting rounding don't do the rounding.

无可置疑 2024-07-15 22:31:10

这是简单的数学。 给定数字 X 和舍入因子 N,公式为:

round(X / N)*N

It's simple math. Given a number X and a rounding factor N, the formula would be:

round(X / N)*N

在梵高的星空下 2024-07-15 22:31:10

综合答案

X = 1234 'number to round
N = 5    'rounding factor
round(X/N)*N   'result is 1235

对于浮点到整数,1234.564到1235,(这是VB特定的,大多数其他语言只是截断):

int(1234.564)   'result is 1235

注意: VB使用银行家四舍五入,到最接近的偶数,如果您不知道的话,这可能会令人惊讶:

msgbox round(1.5) 'result to 2
msgbox round(2.5) 'yes, result to 2 too

谢谢大家.

Integrated Answer

X = 1234 'number to round
N = 5    'rounding factor
round(X/N)*N   'result is 1235

For floating point to integer, 1234.564 to 1235, (this is VB specific, most other languages simply truncate) do:

int(1234.564)   'result is 1235

Beware: VB uses Bankers Rounding, to the nearest even number, which can be surprising if you're not aware of it:

msgbox round(1.5) 'result to 2
msgbox round(2.5) 'yes, result to 2 too

Thank you everyone.

与往事干杯 2024-07-15 22:31:10

舍入到最接近的 X(不是 VBA 特定的)

N = X * int(N / X + 0.5)

其中 int(...) 返回下一个最小的整数。

如果您可用的舍入函数已经四舍五入到最近整数,则省略 0.5 的加法

To round to the nearest X (without being VBA specific)

N = X * int(N / X + 0.5)

Where int(...) returns the next lowest whole number.

If your available rounding function already rounds to the nearest whole number then omit the addition of 0.5

缺⑴份安定 2024-07-15 22:31:10

在 VB 中,math.round 有附加参数来指定小数位数和舍入方法。 Math.Round(10.665, 2, MidpointRounding.AwayFromZero) 将返回 10.67 。 如果数字是小数或单一数据类型,则 math.round 返回小数数据类型。 如果是 double,则返回 double 数据类型。 如果打开了选项严格,这可能很重要。

(10.665).ToString("n2") 的结果从零舍入得到“10.67”。 如果没有额外的参数, math.round 返回 10.66,这可能会导致不必要的差异。

In VB, math.round has additional arguments to specify number of decimal places and rounding method. Math.Round(10.665, 2, MidpointRounding.AwayFromZero) will return 10.67 . If the number is a decimal or single data type, math.round returns a decimal data type. If it is double, it returns double data type. That might be important if option strict is on.

The result of (10.665).ToString("n2") rounds away from zero to give "10.67". without additional arguments math.round returns 10.66, which could lead to unwanted discrepancies.

挽清梦 2024-07-15 22:31:10

'示例:将 499 舍入到最接近的 5。您将使用 ROUND() 函数。

a = inputbox("number to be rounded")
 b = inputbox("Round to nearest _______ ")


  strc = Round(A/B)
  strd = strc*B


 msgbox( a & ",  Rounded to the nearest " & b & ", is" & vbnewline & strd)

'Example: Round 499 to nearest 5. You would use the ROUND() FUNCTION.

a = inputbox("number to be rounded")
 b = inputbox("Round to nearest _______ ")


  strc = Round(A/B)
  strd = strc*B


 msgbox( a & ",  Rounded to the nearest " & b & ", is" & vbnewline & strd)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文