Android Question Problem with decimal rounding

Reinaldo

Member
Licensed User
Longtime User
Hello, have the next number: 16552.225
When apply Round2(number, 2) the result is: 16552.22
But i need that return 16552.23 like Excel.

What function i must use.

Thanks for your help.
 

Roycefer

Well-Known Member
Licensed User
Longtime User
My best guess as to what is going on is that the variable number is of type Float. Due to the reduced precision available as compared to Double, the Float is storing number as 16552.224609375, which will be rounded down to 16552.22 by Round2(). Try Log(number) before your apply Round2() to see what it looks like. If this is, indeed, the case, then you'll be better off storing your numbers as Doubles, rather than Floats. The tiny memory savings are rarely worth it.

The Round2(16552.225,2) will return a Double of value 16552.23 so long as the first argument is of type Double.
 
Upvote 0

pjo12345

Active Member
Licensed User
Longtime User
You can try this:
B4X:
Sub Process_Globals

End Sub

Sub Globals

    Dim x As Double : x=16225.225
    Dim y As Double
End Sub

Sub Activity_Create(FirstTime As Boolean)

    y = cRound(x,2)
    Log("Round: " & y)
End Sub


Sub cRound (Value As Double, decimal As Byte) As Double
  
    decimal = Power(10,decimal) ' Power = 10^decimal
    Value = (Value * decimal) + 0.5
    Dim sma As String
    sma = Value
    If sma.IndexOf(".") <> -1 Then
        sma = sma.SubString2(0,sma.IndexOf("."))
    End If
    Value = sma / 100
    Return Value
End Sub
 

Attachments

  • cRound.zip
    6.5 KB · Views: 305
Upvote 0

Reinaldo

Member
Licensed User
Longtime User
Hi, thanks for your reply , I will apply your recomendations and i will tell your the result.

Informatix, the values are averages.
 
Upvote 0

Reinaldo

Member
Licensed User
Longtime User
You can try this:
B4X:
Sub Process_Globals

End Sub

Sub Globals

    Dim x As Double : x=16225.225
    Dim y As Double
End Sub

Sub Activity_Create(FirstTime As Boolean)

    y = cRound(x,2)
    Log("Round: " & y)
End Sub


Sub cRound (Value As Double, decimal As Byte) As Double
 
    decimal = Power(10,decimal) ' Power = 10^decimal
    Value = (Value * decimal) + 0.5
    Dim sma As String
    sma = Value
    If sma.IndexOf(".") <> -1 Then
        sma = sma.SubString2(0,sma.IndexOf("."))
    End If
    Value = sma / 100
    Return Value
End Sub

Thanks you my friend, your function work fine.
 
Upvote 0
Top