Nice programing

숫자를 가장 가까운 5, 10 또는 X로 반올림

nicepro 2020. 12. 10. 21:07
반응형

숫자를 가장 가까운 5, 10 또는 X로 반올림


499, 73433, 2348과 같은 숫자가 주어지면 가장 가까운 5 또는 10으로 반올림하는 데 사용할 수있는 VBA는 무엇입니까? 또는 임의의 숫자?

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는 가장 가까운 짝수까지 Bankers Rounding을 사용 합니다.

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 데이터 유형을 반환합니다. 엄격한 옵션이 켜져 있으면 중요 할 수 있습니다.

(10.665) .ToString ( "n2")의 결과는 0에서 반올림하여 "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)

엄격한 Visual Basic 접근 방식의 경우 부동 소수점 값을 정수로 변환하여 해당 정수로 반올림 할 수 있습니다. VB는 유형 변환을 반올림하는 드문 언어 중 하나입니다 (대부분의 다른 언어는 단순히 잘림).

5 또는 x의 배수는 라운드 전을 나누고 라운드 후에 곱하기 만하면됩니다.

소수 자리를 반올림하고 유지하려면 Math.round (n, d)가 작동합니다.


솔루션은 다음과 같습니다.

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)

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

이 기능을 사용해보십시오

--------------스타트----------------

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

------------- 끝 ------------


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

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.

참고URL : https://stackoverflow.com/questions/326476/rounding-a-number-to-the-nearest-5-or-10-or-x

반응형