I saw this format function referenced on several sites, but not one of them has an explicit example on how to pass a number to a function.
I tried '12345'.format (' 0.00 '), which, it seems to me, should be written, but it gives me an error that the object does not support the property or method. I also tried Number ('12345'). Format ('0.00'); var num = '12345' // num.format ('0.00'); format ('0.00', '12345') and even tried to use numbers instead of lines 12345.format (0.00). Did I miss something really obvious here?
A copy of the function for the link is included, so you do not need to go to the site (with all the fragments filled).
String.prototype.stripNonNumeric = function() {
var str = this + '';
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;
};
Number.prototype.format = function(format) {
if (!(typeof format == "string")) {return '';}
var hasComma = -1 < format.indexOf(','),
psplit = format.stripNonNumeric().split('.'),
that = this;
if (1 < psplit.length) {
that = that.toFixed(psplit[1].length);
}
else if (2 < psplit.length) {
throw('NumberFormatException: invalid format, formats should have no more than 1 period: ' + format);
}
else {
that = that.toFixed(0);
}
var fnum = that.toString();
if (hasComma) {
psplit = fnum.split('.');
var cnum = psplit[0],
parr = [],
j = cnum.length,
m = Math.floor(j / 3),
n = cnum.length % 3 || 3;
for (var i = 0; i < j; i += n) {
if (i != 0) {n = 3;}
parr[parr.length] = cnum.substr(i, n);
m -= 1;
}
fnum = parr.join(',');
if (psplit[1]) {fnum += '.' + psplit[1];}
}
return format.replace(/[\d,?\.?]+/, fnum);
};