Format currency with mile separator

Asked

Viewed 83,000 times

15

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

However, it only displays values in this format: 1000.00.

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

It would be something like 3 houses before the comma gets dot, I just don’t know how to do it.

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

3 answers

46

You can use the function toLocaleString(), which is part of the prototype of Number. 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"
  • Cool guy, I didn’t know this method. Very good +1.

  • 8

    @Juniornunes I think it’s really cool. There’s even an argument that adds R$ to the string: (1231230123.23).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' }); // => 
"R$1.231.230.123,23"

  • 1

    It only works for situations where you have values after the comma. if the reported value, for example is 1000 the return is 1,000 and not 1,000.00 as expected.

36

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 this:

First take the number and fix it to 2 decimal places and separate the string into a 2-part array (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

So in the second row I can work the number excluding the decimal places (numero[0]), what split, regex and Join do in this part I explain in that reply.

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

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

return numero.join(',');
  • Very cool, that’s what I wanted, but there’s some technical name about it here --> (/(?=(?:...)*$)/) <-- wanted a technical name to research about it and learn everything.

  • @Nicolasguilherme has yes friend, the name of this is Regular expression or regex, you can read more about regular expressions in javascript here, but remembering that there are many other languages that make use of regex.

7

I use this polyfill in my projects.

it creates a method that you can use on all your variables that are of type Number Receive as parameters:

  1. Number of decimals
  2. The symbol you wish to use
  3. The symbol used to separate the thousands
  4. The symbol used to separate decimals

Ex:

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

I believe 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>

  • It has to use without rounding, type 1.200,00 - 3,46 = 1.196,54 instead it shows me 1.196,60... thanks..

  • @Ulissesgimenes from an example of how Voce is using, I would do the account before showing the value. Ex. var valor = 1200 - 3.46; a.formatMoney(2, "R$ ", ".", ",")

  • It’s the way I’m using it, but it seems that now it’s calculating correctly, I think it was browser cache value

Browser other questions tagged

You are not signed in. Login or sign up in order to post.