Follow us on Twitter

Web

jQuery Number Format

by Sam Sehnert

Download jQuery NumberAs-you-type Demo

Check out the updated number format plugin.


The update gives you more options for returning, or replacing numbers, along with as-you-type formatting for input fields!

Original Article:

Don’t you wish there was a way to format numbers using JavaScript, that is as easy, or even easier than PHP’s number formatting functions? I do.

In fact, many of my clients want consistently formatted numbers to be displayed on screen. Usually, I’m already calculating various numbers in JavaScript based on user input, and inserting the raw number into the document using the jQuery .text() function. But that doesn’t give you consistent formatting.

var myNumber = 5000.1;
$('.number').text( myNumber );

// Output: 5000.1

I wanted something which made implementation as simple as possible, because this needed to be used in many places throughout the app, in many different elements, and for several different formats.

I wanted something that was as simple to implement as jQuery’s .text() method.

var myNumber = 5000.1;
$('.number').number( myNumber, 2 ); // 2 decimal places.

// Should output 5000.10

There are loads of great methods around for formatting numbers. My favourite is the excellent phpjs.org library.

To make this even more convenient though, I wrapped it in a jQuery plugin which does the same thing as the .text() method ? with the added ability to format the value with any number of decimal places, specifying the decimal point symbol, and thousands separator symbol.

(function($){

/**
* A quick plugin which implements phpjs.org's number_format as a jQuery
* plugin which formats the number, and inserts to the DOM.
*
* By Sam Sehnert, teamdf.com ? http://www.teamdf.com/web/jquery-number-format/178/
*/
$.fn.number = function( 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');
}
// Add this number to the element as text.
this.text( s.join(dec) );
};

})(jQuery);

The result was, I only needed to change the .text() calls in the rest of my code to something like this:

var myNumber = 5000.1;
$('.number').number( myNumber, 2 ); // 2 decimal places.

// Output: 5,000.10

$('.number').number( myNumber ); // 0 decimal places (rounded).

// Output: 5,000

$('.number').number( myNumber, 1, ',', ' ' );

// Output: 5 000,1

The default values set the decimal as ‘.’, and thousands as ‘,’. Just like PHP’s number_format. Brilliant.

Take a look at the updated number format plugin, which gives you more options for returning, or replacing numbers along with .

Download jQuery NumberAs-you-type Demo

Comments

awake on 06 November, 2014

$.number(5100, 2); //does not work

Sam Sehnert on 06 November, 2014

I've made an addition to the plugin to allow you to return a number using the $.number syntax you suggested above. http://www.teamdf.com/web/jquery-number-format-redux/196/

Steve on 01 October, 2014

There seems to be no way to enter numbers less than 1 (ie 0.75).

Justin Nicholes on 06 February, 2014

Thank you for creating this plugin. My comments are related to the presentation of information on this page. The Yellow color that is used to highlight code is completely unreadable on my monitor and makes it very frustrating to try and navigate your sete.

Ron on 02 June, 2014

This seems to work great until I try $().val() on a control that has a negative number. It returns the absolute value - I always get a positive number back. $("#number").number(true, 2); $("#number").val(-10.23); $("#number").val(); returns 10.23 not -10.23

isuru on 09 September, 2014

After adding this plugin, if someone enter 0 i want to clear text box (" "). if (crisisCapValue == 0) { $("#" + crisisCapId).val(' '); } But it is not working. How can we remove this plugin.

Something to say?

The is a flightless bird and a symbol of NZ

Some HTML is OK
  • <b>bold</b>
  • <i>italic</i>
  • <blockquote>
    blockquote
    </blockquote>
  • <pre>
    preformatted code
    </pre>