Strange JavaScript behaviour on mobile Safari iOS 6

耗尽温柔 提交于 2020-01-02 08:13:14

问题


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:


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!



来源:https://stackoverflow.com/questions/12821635/strange-javascript-behaviour-on-mobile-safari-ios-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!