 # Replace charAt trouble

Hi all!
I am getting a weird error that’s about to drive me crazy.
The scenario is as follows:

I am reformatting a number to fit Norwegian standards. The number before formatting can be something like 1234.01, but needs to look like this: 1.234,00
The function I’ve written works for most numbers, but fails when there are two equal characters next to each other just where the thousand marker period is to be inserted.

That is;
12345.01 works and is converted to 12.345,00
while 22345.01 fails and is converted to 2.2345,00

Heres the code:

``````function numToString(str) {
var numToStr = new String(str);
//first we replace the "." with a ","
numToStr = numToStr.replace(".", ",");
//then we insert a thousand point marker (.)
if ((numToStr.charAt(numToStr.length - 7)!= "-")&&(numToStr.length > 6)) {
numToStr = numToStr.replace(numToStr.charAt(numToStr.length - 7), numToStr.charAt(numToStr.length - 7)+".");
}
//and then a hundred thousand point marker (.)
if ((numToStr.charAt(numToStr.length - 11)!= "-")&&(numToStr.length > 10)) {
numToStr = numToStr.replace(numToStr.charAt(numToStr.length - 11), numToStr.charAt(numToStr.length - 11)+".");
}
return numToStr;
}

trace(numToString(1111.45));

trace(numToString(1234.45));

trace(numToString(11111.45));

trace(numToString(1234.45));

trace(numToString(22620.33));

trace(numToString(12620.33));

trace(numToString(1234567.45));

``````

Does anybody know what’s going on?