decimal numbers

tonga

Member
Licensed User
Longtime User
Hi to all, I wish to know how to compare two decimal numbers.
I have an edit text where an user insert a value between 0.00 and 3.00.
I need to transform the value in 0.01 when the user insert a number under 0.00 and into 3 when the number is over 3.00. I have two problems:
1. the program don't work correctly when it compare a number with one or two decimal, and I've declared the variables with float type (i tryed also 'double').
2. i only need two decimals, how can i do that?
thanks to all
 

klaus

Expert
Licensed User
Longtime User
I suggest you the code below:
B4X:
Dim nb As Double
If EditText1.Text <> "" Then
    nb = EditText1.Text                               ' converts the String into a Double
'    nb = Floor(nb * 100 + 0.5) / 100                  ' rounds to two decimals
    nb = Round2(nb, 2)                               ' rounds to two decimals
    nb = Max(0.01, nb)                                ' sets min value to 0.01
    nb = Min(3.00, nb)                                ' sets max value to 3.00
    EditText1.Text = NumberFormat2(nb, 1, 2, 2, False) ' displays with two decimals
End If
Make sure that you set the InputType type to DECIMAL_NUMBERS.

Best regards.

EDIT: changed the error reported in post #3
 
Last edited:
Upvote 0

MLDev

Active Member
Licensed User
Longtime User
I suggest you the code below:
B4X:
Dim nb As Double
If EditText1.Text <> "" Then
    nb = EditText1.Text                                ' converts the String into a Double
    nb = Floor(nb / 100 + 0.5) * 100    ' rounds to two decimals
    nb = Max(0.01, nb)                                ' sets min value to 0.01
    nb = Min(3.00, nb)                                ' sets max value to 3.00
    EditText1.Text = NumberFormat2(nb, 1, 2, 2, False) ' displays with two decimals
End If
Make sure that you set the InputType type to DECIMAL_NUMBERS.

Best regards.

This line gives the wrong results:
B4X:
nb = Floor(nb / 100 + 0.5) * 100    ' rounds to two decimals

It should be:
B4X:
nb = Floor(nb * 100 + 0.5) / 100    ' rounds to two decimals

Or:
B4X:
nb = Round2(nb, 2)    ' rounds to two decimals
 
Upvote 0
Top