B4J Question Very strange problem adding two numbers

MegatenFreak

Active Member
Licensed User
Hi.
I do some additions in my app, and I ran into this strange problem: when I add 1.3 and 0.1, I get 1.4000000000000001 instead of just 1.4:
B4X:
    Log(1.3 + 0.1)
    Log(1.3 + 0.11)
    Log(1.3 + 0.102)
All of the above result in a large number just like the example. What is strange is that IT ONLY HAPPENS WHEN "3" IS INVOLVED. All other numbers (1.4, 1.5, etc.) work just fine.
I even defined the numbers separately as doubles and then added them. same result. I even tried them as strings.
Please help... I'm so confused.
 

jerry07

Member
Licensed User
Longtime User
If you need to show this as 1.4 and not 1.40000000001 here is example. Not sure if there any other better ways to address this.

B4X:
value1 = 1.3 + 0.1
Log(NumberFormat2(value1, 1, 2, 0, False))

The 3rd parameter will specify number of decimals to show.
 
Upvote 0

MegatenFreak

Active Member
Licensed User
I use NumberFormat (and NumberFormat2) a lot. It's a life saver!
I was just wondering if there's a particular reason, something evil or mysterious about number 3, or if I was doing something wrong.
Fortunately, thanks to Erel, NumberFormat also "rounds" the number to the specified number of fractions, so it also fixes the problem I had with such results as 1.399999...
;)
(p.s. Just in case anyone is interested, this problem arose when I was writing a function to do a "banker" rounding (round to even) on numbers. This method works differently when it tries to round a 5: it rounds it to the nearest higher even number, so, for example, 0.65 rounds to 0.6, but 0.75 rounds to 0.8)
 
Upvote 0
Top