Android Question How use comparation <= operator in float?

Paolo Pini

Member
Licensed User
Longtime User
What is it that I didn't understand?

B4X:
    Dim Value As Float=8.21
    Log(Value <=8.20)    'FALSE'
    Log(Value <=8.21)    'FALSE'?
    Log(Value <=8.22)    'TRUE'
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
I don't like Round2. Both Float and Double cannot 100% accurately represent all values. Using BigDecimal from BigNumber library is one option.

Another one is to use a method such as this one:
B4X:
Public Sub AreEqual(d1 As Double, d2 As Double) As Boolean
 Return Abs(d1 - d2) < 0.000001
End Sub

If value1 < value2 Or AreEqual(value1, value2) Then
 ...
 
Upvote 0

ilan

Expert
Licensed User
Longtime User
this works too:

B4X:
    Dim Value As Float=8.21
    Log(NumberFormat2(Value,1,2,0,False) <=8.20)    'FALSE'
    Log(NumberFormat2(Value,1,2,0,False) <=8.21)    'TRUE'
    Log(NumberFormat2(Value,1,2,0,False) <=8.22)    'TRUE'
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
This is quite hacky. NumberFormat returns a string which is them implicitly parsed to a number. The only reason that it works is that the implicit parsing returns a double which is the same type of the right hand side. I wouldn't consider it safe code.

The correct way to compare two floating point numbers for equality is by dealing with the expected inaccuracy.
 
Upvote 0

Daestrum

Expert
Licensed User
Longtime User
Or make the comparison valid
B4X:
    Dim Value As Float=8.21
    Log(Value <= (8.20).As(Float))    'FALSE'
    Log(Value <= (8.21).As(Float))    'TRUE'
    Log(Value <= (8.22).As(Float))    'TRUE'
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…