How to separate quantities of thousands and decimals by "," and ".", using toLocaleString?

0

Good morning: I have the following amount

var num = 54
var num2 = 1325
var num3 = 1293824

when applying toLocaleString they are left as follows:

num.toLocaleString(undefined, {minimumFractionDigits: 2}) // Resultado 54,00
num2.toLocalString(undefined, {minimumFractionDigits: 2}) // 1.325,00
num3.toLocalString(undefined, {minimumFractionDigits: 2}) // 12.938,24

When I need the results in the following way:

54.00 
1,325.00 
12,938.24

Separator for thousands must be "," Separator for decimals should be "."

Thank you very much in advance.

    
asked by JG_GJ 18.09.2018 в 17:45
source

2 answers

1

You can use the following:

var number = 12345.67;
var result = number.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
console.log(result);
  • .toFixed(2) is the number of decimals you want to leave after the point.
  • .replace(/\d(?=(\d{3})+\.)/g, '$&,'); is an expression Regular that adds the comma after a group of 3 digits.

Greetings!

Source

    
answered by 18.09.2018 / 18:18
source
0

Try this:

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');
    }
    return x1 + x2;
}

var valor = (1325).toFixed(2);
console.log(addCommas(valor));
valor = (1325.25).toFixed(2);
console.log(addCommas(valor));
    
answered by 18.09.2018 в 18:08