I happened to pass across a tiny non-significant bug in Javascript just the other day.
Well, non-significant is in the eye of the beholder... The problem was simple, the user puts an amount to charge using a credit card, verifies the deal is OK from the credit company and does the deal. Nothing special about the process, trust me I've done a few programs which do it. The difference in this case was the interface to the credit company's server, they didn't want a float so we had to send the amount as cents (or agorot in Israel), simple isn't it? Take the amount, multiply by 100, and do whatever.
Simple it isn't. Try to put this line in an HTML script:
alert(parseInt(parseFloat('70.24')*100))
or if you're too lazy just use the following HTML code:
<html>
<head></head>
<body onload="alert(parseInt(parseFloat('70.24')*100))">
</body>
As far as I know 70.24*100 = 7024:) We've found a second problem with 277.9, which has exactly the same bug.
As usual for matters of this kind the solution is to use a "different" approach:
var dol = parseInt(amount.split('.')[0])*100;
var cen = 0;
if (amount.split('.')[1] != null)
{
cen = parseInt(amount.split('.')[1]);
}
if (dol < 0)
{
return dol - cen;
} else {
return + cen;
}
It might not be the best approach, but it certainly does the job. Unless someone fixes the Javascript's variables' accuracy, I'll stick to this solution for this problem.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment