toLocaleString R$ Brazilian

Asked

Viewed 4,625 times

6

I have a simple question about toLocaleString, I didn’t know this prototype and I was testing it instead of doing the good old split and replace

var a = 10000.50
var b = a.toLocaleString('pt-BR')
console.log(b)

The output of this code should be 10.000,50, and not 10.000,5. How does he not ignore the pennies? 'Cause that’s 50 cents, and not 5.

Thank you!

  • 3

    He doesn’t know you want currency formatting.

3 answers

8


This is configurable with the minimumFractionDigits and maximumFractionDigits. If you want to have the decimal number fixed then give the same number to the two. These values can go from 0 to 20.

var a = 10000.50
var b = a.toLocaleString('pt-BR', {
  minimumFractionDigits: 3,
  maximumFractionDigits: 3
})
console.log(b); // 10.000,500

  • 1

    Perfect Sergio! Sensational, man! Thank you =)

5

With the introduction of the API Intl, the toLocaleString can no longer be used, in favor of this new interface, much more complete.

An example:

const number = 1234567.89;

const formatter = new Intl.NumberFormat('pt-BR', {
  style: 'currency',
  currency: 'BRL' 
});

const formatted = formatter.format(number);

console.log(formatted); // R$ 1.234.567,89

To learn more, be sure to consult documentation.

-3

var a = 10000.50
var b = a.toLocaleString('pt-br')
console.log(`${b}0`)

  • The statement that the code produces the output is false 10.000,50. This can be easily checked.

  • Hi, Augusto, I’m new to this medium, and I apologize if the explanation I gave is wrong, but I tried on the console.log and I got the value 10,000.50, as well as predicted.

  • result: https://imgur.com/a/HlSw9Jg

Browser other questions tagged

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