Be careful when doing math on edit controls in Browser code!

I ran into one today, that I haven’t seen in WebDev before. We use to run into a similar problem in that “old language whom’s name shall not be mentioned” when dealing with reals, but this is the first time I have seen this behavior in WebDev and I believe it actually is JavaScript that is really at fault.

Anyway… Take a look at this screenshot.

2019-05-20_1534

If your math skills are above the 1st-grade level, you probably know that 60.73 + 5 = 65.73, not 65.72!. This screen worked correctly with 60.72, but 60.73, and the internet gods get a 1 cent bonus.

The code for this is as about as straight forward as possible.

edtTotalPayment = edtOtherAmount + edtConvenienceFee

That code is in the browser code, no need to do a trip to the server for simple math, right?

If you put in trace statements, you will see that it must be doing the math using reals. Again I suspect this must be a JavaScript thing.

Trace(edtOtherAmount)
Trace(edtConvenienceFee)
Trace(edtOtherAmount + edtConvenienceFee)

Gives you:

60.73
5.00
65.72999999

My first attempt at a fix was:

edtTotalPayment = Round(edtOtherAmount,2)+ Round(edtConvenienceFee,2)

But that still gives the same result, which is why I believe JavaScript must be doing the math using reals.

So to solve the problem and quit donating random pennies to the internet gods, I had to change the line to:

edtTotalPayment = Round(edtOtherAmount + edtConvenienceFee,2)

And the moral of the story is if you have any browser code doing simple math you might want to check it!

 

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s