Android Question Round2 not working fine.

ambg

Member
Licensed User
Longtime User
I have a variable Double with value x=0.565
round2(x,2) return 0.56 incorrect
but if x=1.565
round2(x,2) return 1.57 correct

Are there any function for rounding a number like vb.net (math.round) that work correctly?

Thanks
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
0.565 is a decimal value. It cannot be represented precisely in a double value. In this specific value a very small error will cause the rounding to be unstable.

You can add a small value to make sure that it rounds up:
B4X:
Round2(x + 0.0000001, 2)

With that said, you should avoid using Round2 at all. Use NumberFormat or NumberFormat2 when you want to show the number to the user and keep the more precise value.
You can also use the smart string literal:
B4X:
Log($"Value of x is: $1.2{x}"$)

Note that the rounding method of NumberFormat is HALF_EVEN: https://docs.oracle.com/javase/7/docs/api/java/math/RoundingMode.html#HALF_EVEN

If you want full control over rounding then you should use BigDecimal from the BigNumbers library.
 
Upvote 0
Top