499、73433、2348 のような数値を指定して、どの VBA を使用して最も近い 5 または 10 に丸めることができますか? または任意の数?
5までに:
499 -> 500
2348 -> 2350
7343 -> 7345
10までに:
499 -> 500
2348 -> 2350
7343 -> 7340
等
それは簡単な数学です。数値 X と丸め係数 N を指定すると、式は次のようになります。
ラウンド(X / N)*N
統合された回答
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
みんなありがとう。
最も近い X に丸めるには (VBA 固有ではありません)
N = X * int(N / X + 0.5)
int(...) は次に小さい整数を返します。
使用可能な丸め関数が既に最も近い整数に丸めている場合は、0.5 の追加を省略します
VB では、math.round に、小数点以下の桁数と丸め方法を指定する追加の引数があります。 Math.Round(10.665, 2, MidpointRounding.AwayFromZero)は 10.67 を返します。数値が 10 進数または単一データ型の場合、math.round は 10 進数データ型を返します。double の場合、double データ型を返します。オプション strict がオンの場合、これは重要かもしれません。
(10.665).ToString("n2") の結果は、ゼロから四捨五入されて "10.67" になります。追加の引数がない場合、math.round は 10.66 を返します。これは、望ましくない不一致につながる可能性があります。
'例: 499 を最も近い 5 に四捨五入します。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)
これが私たちの解決策です:
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)
厳密な Visual Basic のアプローチでは、浮動小数点値を整数に変換して、その整数に丸めることができます。VB は、型変換で丸めを行うまれな言語の 1 つです (他のほとんどの言語は単純に切り捨てます)。
5 の倍数または x は、ラウンドの前に割ってラウンドの後に乗算するだけで実行できます。
小数点以下を丸めて保持したい場合は、 Math.round(n, d) が機能します。
この機能を試す
- - - - - - - 始める - - - - - - - -
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
- - - - - - -終わり - - - - - -
単純に ROUND(x/5)*5 で十分です。
コメントが付けられないのでこちらを使用します
vbs でそれを実行し、2 の結果が 2 になる理由を楽しく考えてください。
あなたはラウンドを信頼することはできません
msgbox round(1.5) 'result to 2
msgbox round(2.5) 'yes, result to 2 too
そんな感じ?
'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