Javascript - Numbers to Currency
So a small project recently saw me create (or more accurately complete) a web page to be shown on a large screen tv at work - the idea being the page would track daily install figures and show remaining targets etc.
The problem was the system took numbers from a static file, which was updated daily. The targets were preset and the remaining figures were calculated from these numbers. Obviously using commas and pound signs would mess up the math. I could strip the special characters first, but then I’d have to rebuild the totals with special formatting. If I was going to format the numbers at any point i might as well store them as flat integers and format them everytime i wanted to show them.
So this function takes any number, rounds it to 2 decimal places, inserts commas and adds a pound sign. Swish. To call it, wrap anything you want to display as money in the money function… eg
' + money(array[i]) +';
That was fun. I need to get out more.
<SCRIPT LANGUAGE="JavaScript">
<!-- Kieran Delaney -->
<!-- http://kierandelaney.net/blog -->
<!-- Begin
function money(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
pence = num%100;
num = Math.floor(num/100).toString();
if(pence<10)
pence = "0" + pence;
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+
num.substring(num.length-(4*i+3));
return (((sign)?'':'-') + '£' + num + '.' + pence);
}
// End -->
</script>