B4J Question Double division

jayel

Active Member
Licensed User
Longtime User
Hello,

This code :
B4X:
Sub Process_Globals
    Private fx As JFX
    Private MainForm As Form
    Private Button1 As Button
    Private Label1 As Label
    Private privValue As Double
End Sub

Sub AppStart (Form1 As Form, Args() As String)
    MainForm = Form1
    MainForm.SetFormStyle("UNIFIED")
    MainForm.RootPane.LoadLayout("mainlayout") 'Load the layout file.
    privValue = 0
    MainForm.Show
End Sub

Sub Button1_Action
    Dim addvalue As Int = 10
    privValue = privValue + (1 / addvalue)
   
    Label1.Text = privValue
    Log(privValue)
   
End Sub

when I click the button i get :

Why? I want to get :

0.1
0.2
0.3
0.4
0.5
0.6
.
.
.
2.2
2.3

Somebody help !

Greets

John
 

klaus

Expert
Licensed User
Longtime User
Decimal numbers cannot be expressed exactly in binary form.
Instead of Label1.Text = privValue
use Label1.Text = NumberFormat(privValue, 1, 1)
0.9
1
1.1

EDIT according to post #8.
To force the display of 1 as 1.0
use Label1.Text = NumberFormat2(privValue, 1, 1, 1, False)
0.9
1.0
1.1
 
Last edited:
Upvote 0

jayel

Active Member
Licensed User
Longtime User
Yes,

But when I change my addvalue to 50 ???
Your solution won't work

Not logic the results?
 
Upvote 0

Daestrum

Expert
Licensed User
Longtime User
Sub Button1_Action
Dim addvalue As Int = 10
privValue = privValue + 1
Log(privValue/addvalue)
End Sub
 
Upvote 0

klaus

Expert
Licensed User
Longtime User
@Daestrum

Your code will not avoid a display like 0.30000000000000004 !

Instead of
B4X:
Sub Button1_Action
    Dim addvalue As Int = 10
    privValue = privValue + (1 / addvalue)
  
    Label1.Text = NumberFormat(privValue, 1, 1)
    Log(NumberFormat(privValue, 1, 1))
End Sub

This would be more efficient no need to make the division every time:
B4X:
Sub Button1_Action
    Dim addvalue As Double = 0.1
    privValue = privValue + addvalue
  
    Label1.Text = NumberFormat(privValue, 1, 1)
    Log(NumberFormat(privValue, 1, 1))
End Sub
 
Upvote 0

Daestrum

Expert
Licensed User
Longtime User
It doesn't, but nvm.
 
Upvote 0

jmon

Well-Known Member
Licensed User
Longtime User
You should use NumberFormat2:
B4X:
NumberFormat2(privValue, 1, 1, 1, False)

This way integer numbers will be shown with a .0 behind:
...
0.5
0.6
0.7
0.8
0.9
1.0 '<--
1.1
...
 
Upvote 0

jayel

Active Member
Licensed User
Longtime User
As addValue is normally dynamic value from a database I had to to this the make it work :
B4X:
    Dim addvalue As Int = 50
    privValue = privValue + (1 / addvalue)
    Dim strprivalue  As String = NumberFormat(privValue, 1, 4)
    Label1.Text = strprivalue
    Log(strprivalue)


This code was for testing only, addValue is a value that is retrieved from a table in a database
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…