iOS Question Round2 in B4i

ilan

Expert
Licensed User
Hi,

use NumberFormat ;)

Jan

numberformat does not round correctly:

Log(NumberFormat(2.545,1,2)) = 2.54
Log(Round2(2.545,2)) = 2.55
 
Upvote 0

JanPRO

Well-Known Member
Licensed User
@ilan: you are correct.

I have created a little Round2 Sub:
B4X:
Sub Round2(Number As Double,DecimalPlaces As Int) As Double
   Dim NaObj As NativeObject
   NaObj = NaObj.Initialize("NSNumber").RunMethod("numberWithDouble:",Array(Number))
   
   Dim strNumber As String = NaObj.GetField("stringValue").AsString
   Dim DotIndex As Int = strNumber.IndexOf(".")
   Dim NumberOfDecimalPlaces As Int = strNumber.Length - DotIndex -1
   
   If DecimalPlaces >= NumberOfDecimalPlaces Then
     Return Number
   End If
   
   If Not(DecimalPlaces = 0) Then
     Dim LastNumber As Int = strNumber.SubString2(DotIndex + DecimalPlaces,DotIndex + DecimalPlaces+1)
   Else
     Dim LastNumber As Int = strNumber.SubString2(DotIndex + DecimalPlaces -1,DotIndex + DecimalPlaces)
   End If
   Dim NumberBefore As Int = strNumber.SubString2(DotIndex + DecimalPlaces +1,DotIndex + DecimalPlaces+2)
   
   If NumberBefore > 4 Then
     LastNumber = LastNumber +1
   End If
   
   If Not(DecimalPlaces = 0) Then
     Dim RoundedNumber As Double = strNumber.SubString2(0,DotIndex + DecimalPlaces) & LastNumber
   Else
     Dim RoundedNumber As Double = strNumber.SubString2(0,DotIndex + DecimalPlaces -1) & LastNumber
   End If
   
   Return RoundedNumber
End Sub
 
Last edited:
Upvote 0

Erel

Administrator
Staff member
Licensed User
You should use NumberFormat.
2.545 cannot be represented 100% accurately in a binary system. So in this case the actual value is a bit smaller than 2.545 and it gets rounded down.
2.55 is not closer to the actual value than 2.54.

If it really bothers you then you can use this sub:
B4X:
Sub RoundUpNumberFormat(d As Double, integers As Int, fractions As Int) As String
   Return NumberFormat(d + 0.0000001, integers, fractions)
End Sub
 
Upvote 0
Top