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("");
}
}); |
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:'.'
}); |
Math.formatNumber('4204204.420',{
decimals:2,
currency:true,
currencySymbol:'$ ',
formatWhole:true,
wholeDelimiter:',',
decimalDelimiter:'.'
});
You don’t say?