Formatting value with Numeraljs

Asked

Viewed 535 times

1

I need to format a value for the Brazilian monetary format, R$ 0.000,00. But in the database the values are in decimal, in the format 0.00.

But when the value 20.00 is used, I get 2000 and not 20. I wonder if I’m doing something wrong? I’ve seen the documentation but found nothing about values with 2 houses.

var valuePrince = numeral(20.00);
var valueFormat = valuePrince.format('$ 0,0.[00]');

I’m using version 2.0.6 of Numeral.js.

1 answer

2


In Javascript, as there is only one numeric type (excluding the bigint), there is no proper distinction between a int and a float. Therefore, 20.00 is the same thing as 20.

So on your call to numeral, you are, deep down, doing the following:

numeral(20);

Take an example:

function test(num) {
  console.log(num);
}

test(20.33); // 20.33
test(20.00); // 20

Moreover, Numeral.js does not support Brazilian monetary format natively. You must register it so you can use it. So:

// Todas as opções podem ser encontradas em:
// http://numeraljs.com/#locales
numeral.register('locale', 'pt-BR', {
  delimiters: {
    thousands: '.',
    decimal: ','
  },
  currency: {
    symbol: 'R$'
  }
});

numeral.locale('pt-BR');

const price = numeral(20.00);
const formatted = price.format('$ 0,0.00');

console.log(formatted); // R$ 20,00
<script src="//cdnjs.cloudflare.com/ajax/libs/numeral.js/2.0.6/numeral.min.js"></script>


Interestingly, if your environment supports it, you can use the API Intl.NumberFormat, that gives you a much more robust interface, natively, and that still supports several languages.

So to format a number for the Brazilian monetary format using this API, you can do so:

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

console.log(formatter.format(20)); // R$ 20,00
console.log(formatter.format(1234567.89)); // R$ 1.234.567,89

  • Formidable his answer, as the answer came from the back end, and as it is not strongly typed, probably he should recognize that it was a string, I used the NUMBER(prince), and I did as you said gave it right. thank you

Browser other questions tagged

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