How can I display a number separated by a point for every 3 houses?

4

How can I format values like this: 1.000 or 150.000 or 42.000 ?

My code is this:

var f02 = 42000;
console.log(parseInt(f02));

I need the formatting of the f02 variable to be: 42.000 , and when the number is greater the formatting suits, eg: 150.000 or 1.000.000

    
asked by anonymous 10.10.2016 / 19:44

1 answer

5

One option is the Number.toLocaleString method:

function formatarValor(valor) {
    return valor.toLocaleString('pt-BR');
}

console.log(formatarValor(42000));
console.log(formatarValor(150000));
console.log(formatarValor(1000000));

Using the locale pt-BR , the numbers will be formatted as you want, with . , if you want to use , , use another locale , for example: en-US .

If you need to display the fractional part, use the parameter minimumFractionDigits followed by the minimum number of digits:

function formatarValor(valor) {
    return valor.toLocaleString('pt-BR', { minimumFractionDigits: 2 } );
}
    
10.10.2016 / 19:55