Number Formatter for Javascript with Prototype

So i had to fix a ROI calculator on a client’s website today. Whoever added the content used some script they found that was using jQuery, which of course was totally screwed by Prototype…..soooo, I decided to convert the script to use prototype. One part of the script was using jQuery’s number format plugin. I then delved into extending javscript’s native Math object to have a format number function.

You can see a demo here: Number Format Demo. It has some options for adding commas to the whole number, number of decimal places to show, format for currency, and more….

Download: numberFormat.js

I finally ended up with this slick code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
Object.extend(Math, {
	formatNumber:function(n, options){
		var options = Object.extend({
			decimals:0,
			currency:false,
			currencySymbol: '$ ',
			formatWhole:true,
			wholeDelimiter:',',
			decimalDelimiter:'.'
		},options);
 
		var nArr = new Array();
		nArr = String(n).split('.');
 
		var whole = (typeof nArr[0]!='undefined')?nArr[0]:'0';
		if(options.formatWhole){
			var exp = /(\d+)(\d{3})/;
			while (exp.test(whole)) {
				whole = whole.replace(exp, '$1' + options.wholeDelimiter + '$2');
			}
		}
 
		if(typeof nArr[1]!='undefined'){
			var remainder = nArr[1];
		}else{
			var remainder = '';
			for(var i=0;i<options.decimals;i++){remainder += '0'}
		}
 
		var pfix = options.currency?options.currencySymbol:'';
 
		if(options.decimals<=0) return pfix + whole;
 
		var a = new Array();
		for(var i = 0; i < options.decimals; i++){
			if(remainder.charAt(i) != '') a[i] = remainder.charAt(i);
			else a[i] = '0';
		}
 
		return pfix + whole + options.decimalDelimiter + a.join("");
	}
});

To use the object extension, try this:

1
2
3
4
5
6
7
8
Math.formatNumber('4204204.420',{
	decimals:2,
	currency:true,
	currencySymbol:'$ ',
	formatWhole:true,
	wholeDelimiter:',',
	decimalDelimiter:'.'
});

3 Comments to Number Formatter for Javascript with Prototype

  1. Lance's Gravatar Lance
    May 20, 2010 at 3:02 pm | Permalink

    Thanks. I was thinking i was going to have to write one myself. I have not tried it out yet, but it looks to have the functionality i was looking for.

  2. Max's Gravatar Max
    August 10, 2010 at 1:55 pm | Permalink

    Nice job on the number format JS!

    I took your code and rewrote it. I slimmed it up by eliminating some options and gave it some extra conditionals for a performance speed up.

    If you want a copy, email me > max at bigroomstudios.com

    Thanks!

  3. Federico's Gravatar Federico
    August 27, 2010 at 5:07 pm | Permalink

    Thank, this help a lot 😉

Leave a Reply

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>