Formatting numbers in html : adding space between millions (like : 9 999 999)

2.8k Views Asked by At

I need to display a number in HTML with spaces between its millions, is there any easy formatting that allows to do so?

I want to display 999 999 999, instead of 999999999

4

There are 4 best solutions below

2
On BEST ANSWER

As I stated in my comment. You will not be able to format the number in the way you want using HTML. You will have to use JavaScript.

Here is how you would do it using plain JavaScript.

For reference:

function formatNumber(n) {
  if (n < 0) { throw 'must be non-negative: ' + n; } 
  if (n === 0) { return '0'; }
  
  var output = [];
  
  for (; n >= 1000; n = Math.floor(n/1000)) {
    output.unshift(String(n % 1000).padStart(3, '0'));
  }
  output.unshift(n);
  
  return output.join(' ');
}
1
On

You would need to use PHP to generate the HTML how you would like it displayed, or, alternatively you could use Javascript as Dwayne above has stated. Unfortunately, HTML (or CSS) has no way of formatting numbers like you want.

Check out PHP's number_format() function: http://php.net/number_format

For Javascript, there's a few options (I searched for 'Javascript number currency format' in Google): http://numeraljs.com/

Hope this helps!

1
On

The accepted answer yields wrong results if you ha an number like 123000456 (if I had more point it would have been a comment...)

0
On

A one liner version:

[..."1230000456"].reverse().reduce((acc, v, i) => acc.push((i + 1) % 3 == 0 ? " " + v : v) && acc, []).reverse().join("").trim();