Multi-Format Number

So for this project that I’m working on, I have to be able to format a number to be comma separated and decimalised (only if the decimal numbers aren’t 00) to two decimal places (with rounding – when there is 3 or more decimal places). So, unfortunately there isn’t any actual predefined function out there for any of this. So through the Math.round(), Math.pow() and String.replace() functions, I managed to cobble something together that works flawlessly:


function formatPrice(x){

x = x.split('.');
while(/(\d+)(\d{3})/.test(x[0]))
x[0] = x[0].replace(/(\d+)(\d{3})/, "$1" + "," + "$2");
x[1] = (typeof x[1] != 'undefined'? (!x[1].match(/^00?$/)? "." : "") + x[1].replace(/^(\d{3,})$/, function($1){return Math.round((($1)/Math.pow(10, $1.length))*100);}).replace(/^00$/, '').replace(/^(\d)$/, "$1" + "0") : "");
return x[0] + x[1];

}

Just to show what it does, here is some testing that I did with the code. Original number on the left, new number on the right:

1000 -> 1,000
1000.1 -> 1,000.10
1000.00 -> 1,000
0.00 -> 0
0.1 -> 0.10
0.10 -> 0.10
1000.1236123 -> 1,000.12
1000.1276123 -> 1,000.13



Comments are closed.