Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to format a number in jQuery

I'm trying to work with jQuery's slider plugin and it works great, only I need to format the output into a readable number, with commas such as 30,402,424 as opposed to 30402424.

I know it's possible with javascript but the only ways I've found are very long winded. I've created a fiddle so you can see what I mean...

http://jsfiddle.net/EX5U7/

like image 748
Liam Avatar asked Nov 25 '25 11:11

Liam


2 Answers

Javascript itself does not have support for formatting the numbers as you need, but with some googling I found the following familiar solution that I have used in the past, somewhat revised for better code quality.

function addCommas(numberString) {
  numberString += '';
  var x = numberString.split('.'),
      x1 = x[0],
      x2 = x.length > 1 ? '.' + x[1] : '',
      rgxp = /(\d+)(\d{3})/;

  while (rgxp.test(x1)) {
    x1 = x1.replace(rgxp, '$1' + ',' + '$2');
  }

  return x1 + x2;
}

Source: http://www.mredkj.com/javascript/numberFormat.html

Updated fiddle: http://jsfiddle.net/EX5U7/8/


Here's another solution, which implements PHP's number_format function in Javascript, allowing you to do even more than just blatantly add commas every 3 numbers:

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);
}

Usage: number_format(123456.789, 2, '.', ','); results in 123,456.79

Source: http://phpjs.org/functions/number_format:481

Fiddle: http://jsfiddle.net/EX5U7/10/

like image 84
Nico Avatar answered Nov 28 '25 02:11

Nico


Use the following addCommas method :

function addCommas(nStr)
{
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

Working example : http://jsfiddle.net/EX5U7/1/

like image 22
Manse Avatar answered Nov 28 '25 02:11

Manse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!