Javascript get decimal and thousands separator from NumberFormat

1.8k Views Asked by At

I'm looking for a method to get decimal and thousands separators from NumberFormat object.

var de = new Intl.NumberFormat('de-DE');

Later I plan to use them to parse formated string back to Javascript's float. I know I could create sample number and then scan it with regex but I feel there must be some easier method to get those separators.

2

There are 2 best solutions below

1
On

Here the js function which will return formatted

function customNumberFormat( num){
    var parts = (''+ (num<0?-num:num)).split("."), s=parts[0], i=L= s.length, o='',c;
    while(i--){ o = (i==0?'':((L-i)%3?'':','))+s.charAt(i) +o }
    return (num<0?'-':'') + o + (parts[1] ? '.' + parts[1] : ''); 
}
2
On

Seems you can avoid doing the parsing yourself:

Intl.NumberFormat('de-CH').v8Parse(
    Intl.NumberFormat('de-CH').format(1000) // => 1'000
) // => 1000

But this sounds very chrome-specific :)

But if I were you I'd avoid parsing localized numbers represented as strings to numbers if I can.