Android Question Double Type & Decimals

luke2012

Well-Known Member
Licensed User
Longtime User
Hi to all,
I'm trying to handling a decimal problem on a Double object.

After some computation on that double value, I got this kind of results:

Result 1 = 10.70
Result 2 = 5.50
Result 3 = 6.6999999999999999

My target is to obtain a number format like Result 1 and Result 2.
There is a object / internal IDE function that allow to set the decimals to 2 digits?

P.S.
After i post this question, I found this post:

https://www.b4x.com/android/forum/threads/problem-with-decimal-rounding.60308/
 

wonder

Expert
Licensed User
Longtime User
B4X:
'Rounds the given number to 2 decimal places
Round2(6.6999999999999999, 2)
 
Upvote 0

luke2012

Well-Known Member
Licensed User
Longtime User
B4X:
'Rounds the given number to 2 decimal places
Round2(6.6999999999999999, 2)

Thanks @wonder :)
So in this case the result should be: 6.69 or 6.70 ?

The function is called "round" so I suppose that the result is 6.70 :)
 
Last edited:
Upvote 0

wonder

Expert
Licensed User
Longtime User
Yes, 6.70 if I'm not mistaken. To get 6.69 you could do the following:
B4X:
Sub Truncate(value as Double, decimalPlaces As Int) As Double
    Dim multiplier = Power(10, decimalPlaces) As Int
    Dim result = value * multiplier As Int
    Return (result / multiplier)
End Sub

'Usage:
Result3 = Truncate(69.999999999999, 2)
 
Last edited:
Upvote 0

luke2012

Well-Known Member
Licensed User
Longtime User
Note that in most cases it is a mistake to use Round2.

You should instead use NumberFormat or NumberFormat2 when you show the number.

@Erel, please can you show an example to reach the same target using NumberFormat / NumberFormat2 * ?

* In my case I have an order price (total), and I'll show it in € format (euro.cents)

I suppose: NumberFormat(DoubleVal, 1, 2)
 
Last edited:
Upvote 0
Top