How to format currency in javascript

{0 Comments}

Following is the JavaScript which will help to format currency especially for dollars. 

 Javascript |  copy code |? 
01
<SCRIPT LANGUAGE="JavaScript">
02
 
03
function formatCurrency(num) {
04
num = num.toString().replace(/\$|\,/g,'');
05
if(isNaN(num))
06
num = "0";
07
sign = (num == (num = Math.abs(num)));
08
num = Math.floor(num*100+0.50000000001);
09
cents = num%100;
10
num = Math.floor(num/100).toString();
11
if(cents<10)
12
cents = "0" + cents;
13
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
14
num = num.substring(0,num.length-(4*i+3))+','+
15
num.substring(num.length-(4*i+3));
16
return (((sign)?'':'-') + '$' + num + '.' + cents);
17
}
18
</script>
19

Leave a Comment

Your email address will not be published.