Javascript

5 Missing Javascript Number Format Functions

Written by Kevin Liew on 08 Nov 2011
58,645 Views • Shares
13 comments

Introduction

I wasn't planning to prepare this article at all, but one of my projects I'm working on requires to format numeric value in currency format (2 decimal points) and display it nicely with comma separator for every third digit. Well, Javascript does't have built in methods to format number according to my needs, so I did a few searches on Google and found some really useful number format functions which I think worthwhile to be mentioned.

I found 5 type of javascript number format functions which do different formatting and some of them have more than one solutions, however, if you've a cool number format function, do share it with us.

Round Decimal Points

These two Javascript functions round numbers to the nearest hundredth, with two digits following the decimal point. This is extremely useful when displaying prices or the totals of orders.

Solution #1

function CurrencyFormatted(amount) {
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
}

/**
*	Usage: 	CurrencyFormatted(12345.678);
*	result:	12345.68
**/

Source: Will Master

Solution #2

function format_number(pnumber,decimals){
	if (isNaN(pnumber)) { return 0};
	if (pnumber=='') { return 0};
	
	var snum = new String(pnumber);
	var sec = snum.split('.');
	var whole = parseFloat(sec[0]);
	var result = '';
	
	if(sec.length > 1){
		var dec = new String(sec[1]);
		dec = String(parseFloat(sec[1])/Math.pow(10,(dec.length - decimals)));
		dec = String(whole + Math.round(parseFloat(dec))/Math.pow(10,decimals));
		var dot = dec.indexOf('.');
		if(dot == -1){
			dec += '.'; 
			dot = dec.indexOf('.');
		}
		while(dec.length <= dot + decimals) { dec += '0'; }
		result = dec;
	} else{
		var dot;
		var dec = new String(whole);
		dec += '.';
		dot = dec.indexOf('.');		
		while(dec.length <= dot + decimals) { dec += '0'; }
		result = dec;
	}	
	return result;
}

/**
*	Usage: 	format_number(12345.678, 2);
*	result:	12345.68
**/

Source: Java-script.net

Solution #3

function round(number, decimals){
	return parseFloat(number.toFixed(decimals));
}

Source: Hott dogg

Add Commas

These two javascript functions add commas between every third digit (right to left) for numbers 1000 and larger. This makes big number easier to comprehend.

Solution #1

function CommaFormatted(amount) {
	var delimiter = ","; // replace comma if desired
	amount = new String(amount);
	var a = amount.split('.',2)
	var d = a[1];
	var i = parseInt(a[0]);
	if(isNaN(i)) { return ''; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	var n = new String(i);
	var a = [];
	while(n.length > 3)
	{
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	if(n.length > 0) { a.unshift(n); }
	n = a.join(delimiter);
	if(d.length < 1) { amount = n; }
	else { amount = n + '.' + d; }
	amount = minus + amount;
	return amount;
}

/**
*	Usage: 	CommaFormatted(12345678);
*	result:	12,345,678
**/

Source: Will Master

Solution #2

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

/**
*	Usage: 	addCommas(12345678);
*	result:	12,345,678
**/

Source: Darian Cabot

Number Format, ported from PHP

This Javascript function is designed to perform the same functionality of php number_format function. This function able to round and put comma on a give float number. Also, you will able to customise the symbols for decimal point and the thousands separator.

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, '.', ',');
*	result:	123,456.79
**/

Source: phpJS

Add an ordinal for counting numbers

This javascript function adds an ordinal to a number. For example, st, nd, rd and th

Number.prototype.toOrdinal = function() {
	var n = this % 100;
	var suffix = ['th', 'st', 'nd', 'rd', 'th'];
	var ord = n < 21 ? (n < 4 ? suffix[n] : suffix[0]) : (n % 10 > 4 ? suffix[0] : suffix[n % 10]);
	return this + ord;
}

/*
*	Usage:
*	var myNumOld = 23 
*	var myNumNew = myNumOld.toOrdinal()
*	Result: 23rd
*/


Source: Darian Cabot

Strip Non-numeric Character from a String

This javascript functions removes all non-numeric characters from string.

function stripNonNumeric( str )
{
  str += '';
  var rgx = /^d|.|-$/;
  var out = '';
  for( var i = 0; i < str.length; i++ )
  {
    if( rgx.test( str.charAt(i) ) ){
      if( !( ( str.charAt(i) == '.' && out.indexOf( '.' ) != -1 ) ||
             ( str.charAt(i) == '-' && out.length != 0 ) ) ){
        out += str.charAt(i);
      }
    }
  }
  return out;
}

/*
*	Usage: stripNonNumeric('123et45dhs6.789'); 
*	Result: 123456.789
*/

Source: Netlobo

Off topic

During the search, I found an interesting fact about number

Letters 'a', 'b', 'c' & 'd' do not appear anywhere in the spellings of 1 to 99
(Letter 'd' comes for the first time in Hundred)

Letters 'a', 'b' & 'c' do not appear anywhere in the spellings of 1 to 999
(Letter 'a' comes for the first time in Thousand)

Letters 'b' & 'c' do not appear anywhere in the spellings of 1 to 999,999,999
(Letter 'b' comes for the first time in Billion)

And
Letter 'c' appears in octillion which is 1,000,000,000,000,000,000,000,000,000

Hope you enjoy this post! If you want more, please follow us or subscribe our RSS.

Join the discussion

Comments will be moderated and rel="nofollow" will be added to all links. You can wrap your coding with [code][/code] to make use of built-in syntax highlighter.

13 comments
Hott Dogg 5 years ago
Oh, c'mon!
Round Decimal Points:

function round(number, decimals){
return parseFloat(number.toFixed(decimals));
}
Reply
Hott Dogg 4 years ago
Solution # 2 under "Add Comma" does not work because of several errors. First error on line 5 of the solution the immediate if is improperly formatted

var x2 = x.length >; 1 ? '.' + x[1] : '';

should be written like this

var x2 = (x.length > 1) ? '.' + x[1] : '';

And the regular expression

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

does not execute. I do not use regular expression, so I don't know the fix here. Too bad because the function looked nice and simple.
Reply
Dragos 4 years ago
HI!

Add Commas functions doesn't work :(
Reply
JustTryingToHelp 4 years ago
In the number_format function, I had to change the syntax of the RegEx replace slightly to escape some of the metacharacters to get it to work:

s[0] = s[0].replace(/B(?=(?:d{3})+(?!d))/g, sep);
Reply
Pete 4 years ago
With thanks to Darian Cabot for the addCommas function, here is a tweaked version that worked better for me. I added backslashes before "d" in the regex and dealt differently with numbers lacking decimal points.

function addCommas(nStr) {
nStr += '';
var x = nStr.split('.');
var x1 = x[0];
var x2 = x[1];
if (typeof x2 !== 'undefined') { x2 = '.' + x[1]} else { x2 = ''}
var rgx = /(d+)(d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
Reply
peter 4 years ago
Page (in solution) + forum error
var rgx = /(d+)(d{3})/;
backslah+d = digit for reg. exp
http://www.regexp.cz/
May be, you must use double slash \d
Reply
peter 4 years ago
Or, you can use [0-9] as digit.
And, i found error 2:
str = '0123';
parset as '0 123'
Reply
siller 3 years ago
CommaFormatted and addCommas functions dont work.
Reply
Adam 4 years ago
Just created a js library to make it easy to format numbers Numeral.js. http://adamwdraper.github.com/Numeral-js/
Reply
Brandon 4 years ago
There is a very cool example which uses an even shorter version of this function which can be applied to one number or a string full of numbers on Chris West's blog. I found it here:
http://gotochriswest.com/blog/2012/09/28/javascript-number-getordinalfor/
Reply
David Almeida 4 years ago
In the number_format function, there is a mistake.
If the decimal separator (dec_point) is sent as a param, on line 20,
it shouldn't be: .split('.');
but: .split(dec_point);
Reply
David 4 years ago
Please remove my previous comment.
I make a confusion. The problem wasn't the split param, it was the reg exp.
Sorry :-)
Reply
nikhil patel 3 years ago
modified function stripNonNumeric because its not giving proper output

function stripNonNumeric(str){

var rgx = /[\d\.]+$/
var outstr='';
for( var i = 0; i < str.length; i++ )
{

if(rgx.test(str.charAt(i))){
outstr = outstr+str.charAt(i);
}
}
return outstr;
}
Reply