user2505081
user2505081

Reputation: 1

Javascript Math Replacing Dots/Decimals with Commas

I'm using a math javascript and I'm having some trouble getting it to replace commas for dots and dots for commas. I can get the comma for the thousands seperator to change but can't manage to get the decimal point to turn into a comma. I tried a number of suggestions from other posts with no joy. The goal is to achieve number formatting for a Greek application.

Here's what I have:

function addCommas(nStr) {
    nStr += '';
    x = nStr.split(',');
    x1 = x[0];
    x2 = x.length > 1 ? ',' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
        x2 = x.replace(/,([^,]*)$/, ".$1");
    }
    return x1 + x2;
}

function addCommas2(nStr, nztr) {
    var sam = nStr.toFixed(nztr);
    return sam;
}

function roundNumber(num, dec) {
    return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);

}

Upvotes: 0

Views: 1734

Answers (2)

BGerrissen
BGerrissen

Reputation: 21690

Here's a pragmatic approach:

var newString = '2,000.80'.replace(',','#').replace('.',',').replace('#','.');
//> '2.000,80'

Basically replace one character with a dummy character and replace that later on.

Upvotes: 2

Erik Schierboom
Erik Schierboom

Reputation: 16656

I would recommend using the Globalize library. It allows you to do globalization of numbers easily. The following example is taken from the documentation page and shows to output a number using a specific culture:

Globalize.culture( "en" );
Globalize.format( 1234.567, "n" ); // "1,234.57"

Globalize.culture( "nl" );
Globalize.format( 1234.567, "n" ); // "1.234,57" - note that the comma and dot are switched

I have created a small sample project that shows how to use this library for client-side globalization: https://github.com/ErikSchierboom/clientsideglobalization

Upvotes: 0

Related Questions