Valentin Radu
Valentin Radu

Reputation: 649

Cannot round up a number

I have the following code:

Dim a as Long
a = InputBox("a=")
Dim nr_cifre as Long
nr_cifre = 0
Dim n as Long
n=a
Do While n <> 0
    n=n / 10
    nr_cifre = nr_cifre + 1
Loop
If a - a mod (10 * nr_cifre) = 0.5 Then
    a=a+0.9+(nr_cifre*10)
End If
MsgBox a mod (10 * nr_cifre)

Basically, it tries to round up numbers. So, 2.3 will become 2. Also, it tries to round up, for example, 2.5 to 3.

The example works for small numbers, like 1234,5. But if I try to round up 12345,6, it gives me some weird errors. I have also tried the code in VB6, but without success.

May I ask for your help/suggestions? Any tip is highly appreciated. Thanks in advance!

Upvotes: 2

Views: 5874

Answers (1)

Panayot Karabakalov
Panayot Karabakalov

Reputation: 3179

If you need your own algorithm then try this:

WSH.Echo CustomRound(-123456.7) '-123457
WSH.Echo CustomRound(-123456.5) '-123456
WSH.Echo CustomRound(-123456.3) '-123456
WSH.Echo CustomRound(123456.7)  '123457
WSH.Echo CustomRound(123456.5)  '123457
WSH.Echo CustomRound(123456.3)  '123456

Function CustomRound(nValue)
    CustomRound = Int(nValue + 0.5)
End Function

or...

WSH.Echo CustomRound2(-123456.7) '-123457
WSH.Echo CustomRound2(-123456.5) '-123457
WSH.Echo CustomRound2(-123456.3) '-123456
WSH.Echo CustomRound2(123456.7)  '123457
WSH.Echo CustomRound2(123456.5)  '123457
WSH.Echo CustomRound2(123456.3)  '123456

Function CustomRound2(nValue)
    CustomRound2 = Sgn(nValue) * Int(Abs(nValue) + 0.5)
End Function

Well... one more idea :)

Function RoundFrm(nValue)
    RoundFrm = Null
    If IsEmpty(nValue) Or _
    Not IsNumeric(nValue) Then Exit Function
    RoundFrm = FormatNumber(nValue, 0)
End Function

And using above idea can make more complete function like...

Function RoundEx(nValue)
    Select Case VarType(nValue)
        Case vbInteger, vbLong
            RoundEx = nValue
        Case vbSingle
            RoundEx = CSng(FormatNumber(nValue, 0))
        Case vbDouble
            RoundEx = CDbl(FormatNumber(nValue, 0))
        Case vbCurrency
            RoundEx = CCur(FormatNumber(nValue, 0))
        Case Else: RoundEx = Null
    End Select
End Function

Upvotes: 4

Related Questions