is there a problem with round?

Subu

Member
Licensed User
A line of code:

i = Round(11.5*100/100)

gives i as 12, but the following code:

= Round(10.5*100/100)

gives i as 11, why?
 

mjcoon

Well-Known Member
Licensed User
Why do you think that is wrong? It is traditional/conventional to round 0.5 upwards.

Seems consistent to me...

Mike.
 

Subu

Member
Licensed User
A line of code:

i = Round(11.5*100/100)

gives i as 12, but the following code:

i= Round(10.5*100/100)

gives i as 10, why? it should be 11

Sorry original question was wrong i wrote 11 instead of 10.
 
Last edited:

Subu

Member
Licensed User
thank you, i did read that article
I made this sub to perform normal rounding, it works till two decimal points:

B4X:
Sub RoundOf (Iinput)' My own sub to handle bug of Round (10.5) = 10
'BUG SOURCE: Only works till 2 dp
   DecimalPart = 100 * (Iinput - Int(Iinput))
   If DecimalPart >= 45 Then 
      Return Int(Iinput)+ 1
   Else
      Return Int(Iinput)
   End If
End Sub
 

Discorez

Member
Licensed User
Longtime User
Try it:

B4X:
Sub RoundEx(Num, Prec)
    FracPart = Frac(Num) * Prec
    Temp = Frac(FracPart)
    FracPart = Int(FracPart)
    If Temp >= 0.5 Then FracPart = FracPart +1
    If Temp <= -0.5 Then FracPart = FracPart -1
    Return Int(Num) + FracPart / Prec
End Sub

Sub Frac(Num)
  Return Num - Int(Num)
End Sub

Prec should be
1 - X
10 - X.X
100 - X.XX
e.t.c.

RoundEx(10.5, 1) 'returns 11
RoundEx(11.5, 1) 'returns 12
RoundEx(11.4, 1) 'returns 11
RoundEx(11.6, 1) 'returns 12
RoundEx(10.5356, 100) 'returns 10.54
 
Top