Space in number format

Viewed 5210

How do I add space as a decimal number separator? The current format is 23456.00 but it has to be 23 456

I got it to remove the .00 with toFixed already but no luck with the space separator.

{{parseFloat(post.meta.price).toFixed(0)}}

Perhaps I can change the locale format in the code to fr-FR because that will add the space?

3 Answers

Perhaps I can change the locale format in the code to fr-FR because that will add the space?

Yes, you can!

price = 23456.00
disp = new Intl.NumberFormat('fr-FR').format(price)
console.log(disp)

reference: Intl.NumberFormat

You can use below function to add a space as a decimal number separator.

function formatNumber(num) {
  return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1 ');
}

console.log(formatNumber(2665));
console.log(formatNumber(102665)); 
console.log(formatNumber(111102665));

Use toLocaleString and replace commas with spaces:

const num = 23456.00;
const res = num.toLocaleString().replace(/,/g, " ");
console.log(res);

Related