Domanda

I currently have a formatNumber function that takes a number and applies some decimal. It is working for me in eveything except IE8.

The following example for some reason prints out: 3.3500.3500000 in IE8 and not 3.500.000 which it's supposed too.

Any idea on what could be failing here?

 function formatNumber(3500000)
{
    var numString = myNum.toString();
    var result = '';

    while (numString.length > 3)
    {
        var chunk = numString.substr(-3);
        numString = numString.substr(0, numString.length - 3);
        result = '.' + chunk + result;
    }

    if (numString.length > 0)
    {
        result = numString + result;
    }

    return result;
}
È stato utile?

Soluzione

Change var chunk = numString.substr(-3); to

var chunk = numString.substr(numString.length - 3, 3);

AND change 3500000 to myNum in your parameter list.

Altri suggerimenti

Q Any idea what could be failing here?

A I believe that IE8 javascript does not support a negative value as an argument for the substr method. I think that's the root of the problem.

That is, the first time through the loop, substr(-3) is interpreted as substr(0), the result is that you get the entire string, rather than the last three characters of the string. That explains the result you are seeing.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top