0

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);

}
cfs
  • 10,610
  • 3
  • 30
  • 43
  • check out the answers to this question: http://stackoverflow.com/questions/1068284/format-numbers-in-javascript – cfs Jun 20 '13 at 12:28
  • 1
    I'm having trouble understanding your problem, could you post an example data, like: `1234,89` becomes `1,234.89` – Anthony Jun 20 '13 at 12:35
  • You want commata for thousand separator *and* for decimal point? Please be more specific about the expected output, maybe add some examples. – Bergi Jun 20 '13 at 12:40
  • The application is a basic calculator. User enters values, hits a calculate button and the result is displayed. When they hit calculate instead a a result being 123,456.78 it needs to be 123.456,78 – user2505081 Jun 20 '13 at 12:53
  • Well, your script seems to do the opposite of what you want. Did you wrote that on your own, or is it an unmodified, ununderstood snippet you found somewhere? Also, what is the `nStr` input? – Bergi Jun 20 '13 at 13:00

2 Answers2

2

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.

BGerrissen
  • 21,250
  • 3
  • 39
  • 40
0

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

Erik Schierboom
  • 16,301
  • 10
  • 64
  • 81