Strange JavaScript behaviour on mobile Safari iOS

2019-05-10 11:06发布

I ran into a very very very strange JS issue that is reproducing only on Mobile Safari browser on iOS 6. The issue is in a function that formats a given value to a price, by stripping down the number to 2 decimals and adds the currency in front of the number. Here are the functions. I will explain later on how to reproduce the bug.

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 the formatCurrency function over and over again (within a setInterval for example) with the same value (lets say value=1; and currency="GBP") you will notice the once every 800-1000 iterations the value return by the function contains a negative amount: GBP-1 instead of GBP1. This issue is very annoying i I did not found any issue within the JS functions.

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

Am I missing something?

1条回答
冷血范
2楼-- · 2019-05-10 11:40

I guess;

text = "-" + String(text);

is the issue.

Me too have been surfing around a lot for iOS6 related bugs in Safari. It seems the JS should be lot more cleaner if we want it to execute smooth!

查看更多
登录 后发表回答