3

So, I have this string, which can contain a number of any length really.

10
100
1000
10000
100000

I need a regex which makes the strings like this:

10
100
1 000
10 000
100 000

For 100000, I have made this: /.{1,3}/g, but that only works from 100 000 and up. Is this possible?

ptf
  • 3,210
  • 8
  • 34
  • 67
  • @kjelelokk Can you please search on google before asking questions here? Please – Andreas Louv Apr 24 '13 at 13:56
  • @NULL I did, guess I have poor Google skills. Also didn't know they were called thousand separators, English isn't my first language. Sorry. – ptf Apr 24 '13 at 14:07

2 Answers2

6

So basically you want thousand separators.

Look into number_format on PHPJS, or use this simplified version:

var num = 10000;
alert((""+num).replace(/\B(?=(?:\d{3})+(?!\d))/g," ")) // 10 000
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

You can take a look at the code on phpjs.

He's created a Javascript function to mimic php's number_format().

This is copy/paste and I stripped comments:

function number_format (number, decimals, dec_point, thousands_sep) {
  number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
  var n = !isFinite(+number) ? 0 : +number,
    prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
    sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
    dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
    s = '',
    toFixedFix = function (n, prec) {
      var k = Math.pow(10, prec);
      return '' + Math.round(n * k) / k;
    };
  // Fix for IE parseFloat(0.55).toFixed(0) = 0;
  s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
  if (s[0].length > 3) {
    s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
  }
  if ((s[1] || '').length < prec) {
    s[1] = s[1] || '';
    s[1] += new Array(prec - s[1].length + 1).join('0');
  }
  return s.join(dec);
}

I take no credit for this code.

Glitch Desire
  • 14,632
  • 7
  • 43
  • 55