user2047861
user2047861

Reputation: 125

Javascript get decimal and thousands separator from NumberFormat

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.

Upvotes: 2

Views: 2006

Answers (2)

djfm
djfm

Reputation: 2458

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.

Upvotes: 1

Mitul
Mitul

Reputation: 3427

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] : ''); 
}

Upvotes: 0

Related Questions