Android Question Round and Round2 for Float data type

Roberto P.

Well-Known Member
Licensed User
Longtime User
Hello to all,
I have read many threads regarding the use of the round and round2 functions, but I do not understand which function is to be used to have a simple rounding of a value contained in a float variable.

I have a float variable that contains 103.70 and is converted with a periodic value (103.69999694824219). considering that this periodic value creates a misalignment of hundredths on the calculations, I thought to use the round functions to be sure to have the value with only two decimals.

But the situation does not change! Because?

What should I use to get a precise rounding?

Here are some examples and related results.


B4X:
Dim aFloat As Float         = 103.70
    Dim aDouble As Double        = 103.70

    Log("Value of float " & aFloat)
    
    Dim aNewFloat As Float    = Round2(aFloat, 2)
    Log("a new float " & aNewFloat)
    
    Dim bNewFloat As Float    = aNewFloat
    Log("b new float " & bNewFloat)
    
    Dim cNewFloat As Float    = Round(aFloat)
    Log("c new float " & cNewFloat)
    
    Dim aNewDouble As Double    = Round2(aDouble, 2)
    Log("d anew double " & aNewDouble)

results

Value of float 103.69999694824219
a new float 103.69999694824219
b new float 103.69999694824219
c new float 104
d anew double 103.7


thank in advance
regards
 

stevel05

Expert
Licensed User
Longtime User
You cannot change the precision of the stored values of Floats or Doubles, Doubles are generally preferred to minimize rounding errors that Floats incur. To display a value with a specified precision you should use NumberFormat, or NumberFormat2
 
Upvote 0

Roberto P.

Well-Known Member
Licensed User
Longtime User
Hi Stevel,

so I can not delete the decimals from the float and double variables? The problem is not the display of data but the calculations altered by decimals.

thank you
 
Upvote 0

stevel05

Expert
Licensed User
Longtime User
Using Doubles instead of floats should minimize calculation issues.
 
Upvote 0

udg

Expert
Licensed User
Longtime User
Another way could be to multiply/divide by 100 your original value and save it as long/int.
Something like:
B4X:
dim mymoney as long = edittext1.text * 100 'assuming edittext contains  a valid decimal number
 
Upvote 0
Top