Format number with Javascript

Asked

Viewed 3,800 times

2

I need to format whole numbers, example:

let num = 1234567;
// saída 1.234.567

However, if the number you are going to have has decimal places that appear to no more than two decimal places. Example:

let num = 1234567.891
// saída 1.234.567,89

let num2 = 123.4
// saída 123,4

That is, if an integer shows formatted with no decimal places, now if a number with decimal places comes up, show 2 places at most.

My code works to some extent, when the size passes 6 it does not format anymore. It is doing so:

let num = 1234567;
// saída 1234.567

Below my code:

export function fmtoNumero(val, n = 2, x = 3, s = '.', c = ',') {       
    let numval = Number(val);
    let re = '\\d(?=(\\d{' + x + '})(\\D|$))';

    numval = numval.toString().replace('.', c);
    numval = numval.replace(new RegExp(re, 'g'), '$&' + (s || ','));
    return numval;
}

2 answers

7


Instead of using regular expressions, you can use Javascript’s native API to achieve the same result more simply.

To fix the number of decimals, you can use the method toFixed:

(999.9).toFixed(2) // "999.90"
(100.158).toFixed(2) // "100.16"

To format the number by separating the thousands by comma, you can use the method toLocaleString:

(987654321).toLocaleString('pt-BR') // "987.654.321"
(9876543.21).toLocaleString('pt-BR') // "9.876.543,21"

However, if you want to combine the two, the most logical would be to chain the two, but this is not the case, since both methods return a string. So let’s just use the method toLocaleString, passing some options as second argument:

(987654.321).toLocaleString('pt-BR', {
  minimumFractionDigits: 2,
  maximumFractionDigits: 2
}) // "987.654,32"

Reference and recommended reading:

3

Complementing the accepted answer, there is still another alternative, which is to use a Intl.NumberFormat. Its operation is similar to toLocaleString:

let formatador = new Intl.NumberFormat('pt-BR',
    { minimumFractionDigits: 0, maximumFractionDigits: 2 }
);

[ 987654.321, 987654321 ].forEach(n => {
    console.log(`formatar ${n} = ${formatador.format(n)}`);
});

According to the documentation, wear a NumberFormat is more advantageous if you need to format a large amount of numbers. And making a basic test, in fact the solution with NumberFormat proved much faster.

Browser other questions tagged

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