Strange JavaScript behavior on a Safari iOS 6 mobile device

I had a very very strange JS problem that can only be played in Mobile Safari on iOS 6. The problem is a function that formats a given value by price, reducing the number to two decimal places and adding the currency in front of the number. Here are the functions. I will talk about how to reproduce the error later.

formatCurrency = function(value, currency, fixedPrecision, colourize, blankIfZero) { var text; if (blankIfZero && (Math.abs(value) < 0.01 || value === undefined)) { return ""; } if (fixedPrecision) { text = currency + Math.abs(value).toFixed(2); } else { text = currency + roundTo2Decimals(Math.abs(value)); } if (value < 0) { text = "-" + text; } if (colourize) { var colorClass = (value < 0 ? "negative" : "positive"); text = "<span class='" + colorClass + "'>" + text + "</span>"; } return text; }; roundTo2Decimals = function(value) { var sign = value < 0 ? -1 : 1; return Math.round(Math.abs(value) * 100.0)/100.0 * sign; }; 

If I run the formatCurrency function again and again (for example, in includeInterval) with the same value (for example, value = 1 and currency = "GBP"), you will notice that once every 800-1000 iterations, the function returns a negative amount: GBP-1 instead of GBP1. This problem is very annoying, I did not find any problems in the JS functions.

I managed to solve the problem ... but I'm curious what the problem is with this implementation. [Edit: I fixed the problem by removing the "-" character from "roundTo2Decimals (Math.abs (value))". But a "-" char should never appear in the first place. So the fix was actually a workaround.]

Did I miss something?

+2
javascript math mobile-safari ios6
source share
1 answer

I guess;

text = "-" + String (text);

- a problem.

I also surfed a lot for iOS6 related errors in Safari. It seems JS should be much cleaner if we want it to run smoothly!

0
source share

All Articles