Format currency with thousands separator [duplicate]

7

I have the following code:

function numberParaReal(numero){
    var formatado = "R$ " + numero.toFixed(2).replace(".",",");
    return formatado;
}

function realParaNumber(texto){
    var compativelComParseFloat = texto.replace("R$ ","");
    compativelComParseFloat = compativelComParseFloat.replace(",",".");
    var valor = parseFloat(compativelComParseFloat);
    return valor;
}

But it only displays values in this format: 1000.00.

I wanted to leave it like this: 1,000.00 ~ 100,000.00 ~ 10,000,000.00 and so on ...

It would be something like 3 houses before the comma gets point, just do not know how to do that.

Probably there should be functions ready for this type of situation, however as I am learning, it would not be ideal to use ready-made functions.

    
asked by anonymous 06.03.2017 / 17:37

3 answers

20

You can use the toLocaleString () function, which is part of the Number prototype. For example, to convert 124231.45 and 1242311234.45 to the Brazilian standard, use, respectively:

(124231.45).toLocaleString('pt-BR'); // => "124.231,45"

(1242311234.45).toLocaleString('pt-BR'); // => "1.242.311.234,45"
    
07.03.2017 / 01:24
19

Using your code I made some modifications:

function numberToReal(numero) {
    var numero = numero.toFixed(2).split('.');
    numero[0] = "R$ " + numero[0].split(/(?=(?:...)*$)/).join('.');
    return numero.join(',');
}

var x = numberToReal(9999000.33);
console.log(x);

var y = numberToReal(100000);
console.log(y);

var z = numberToReal(10.50);
console.log(z);

What I do is the following:

First I get the number and fix it with 2 decimal places and separate the string into an array of 2 parts (before and after the point).

var numero = numero.toFixed(2).split('.');
// Se o número inicial for 100.00, numero[0] será 100 e numero[1] será 00

This way in the second line I can work the number excluding the decimal places ( numero[0] ), what split, regex and join do in that part I explain in this answer .

numero[0] = "R$ " + numero[0].split(/(?=(?:...)*$)/).join('.');

Then just return the formatted number by joining with the decimals using the comma.

return numero.join(',');
    
06.03.2017 / 18:19
3

I use this polyfill in my projects.

It creates a method that you can use in all your variables that are of type Number It receives as parameters:

  • Number of decimal places
  • The symbol you want to use
  • The symbol used to separate the thousands
  • The symbol used to separate the decimals
  • Ex:

    var numero = 123456.78;
    numero.formatMoney(2, "R$ ", ".", ",");
    

    I think I can help you.

    Number.prototype.formatMoney = function(places, symbol, thousand, decimal) {
    	places = !isNaN(places = Math.abs(places)) ? places : 2;
    	symbol = symbol !== undefined ? symbol : "$";
    	thousand = thousand || ",";
    	decimal = decimal || ".";
    	var number = this, 
    	    negative = number < 0 ? "-" : "",
    	    i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
    	    j = (j = i.length) > 3 ? j % 3 : 0;
    	return symbol + negative + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "");
    };
    
    // Aqui para testar
    var a = 3211000.354;
    
    document.getElementById('testP').innerHTML = a.formatMoney(2, "R$ ", ".", ",");
    <p id="testP"></p>
        
    06.03.2017 / 18:00