A little If math problem...

Gary Miyakawa

Active Member
Licensed User
Longtime User
This code used to work (1.5)... I'm not sure what changed (and it certainly could be me)...

B4X:
Sub Process_Globals
End Sub
Sub Globals
   Dim Label1 As Label
   Dim Stepper As Float
End Sub

Sub Activity_Create(FirstTime As Boolean)
   activity.LoadLayout("1")
   Stepper = .01
End Sub

Sub btnStep_Click
   If Stepper = .01 Then
      Stepper = .001
   Else
      Stepper = .01
   End If
   label1.Text = Stepper
End Sub

The goal is that each time I click on the step button, the value of Stepper would change from .01 to .001 (and back)....

But now, it always stays on .01 and never changes....

Any thoughts or suggestions would be greatly appreciated.

Gary M
 

agraham

Expert
Licensed User
Longtime User
This is an old trap people fall into time and time again. Try
B4X:
Dim x As Float
x = 0.01
Msgbox(x,"0.01")
It arises because the binary format of Float and Double cannot accurately represent every decimal number. Floating point operations on computers are effectively always approximations. Where absolute accuracy is required special techniques are required or special types like the Java BigDecimal or the .NET Decimal need to be used.
 
Upvote 0

Gary Miyakawa

Active Member
Licensed User
Longtime User
Bingo, that was it... Set up a variable (Float) with the .01 in it and test against that and it works fine....

Thank you !

Gary M
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
This is related to a fix to this bug: http://www.b4x.com/forum/bugs-wishlist/9780-2-2-66-a.html

When you write 0.01 the compiler treats it as a double number. A float value of 0.01 is not equal to a double value of 0.01 because of the inaccuracy in representing this decimal value. The solution is to change Stepper to be Double instead of Float.
 
Upvote 0
Top