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){
while(/(\d+)(\d{3})/.test(x[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