Efficient money conversion

[Total: 0    Average: 0/5]

Formats a number to U.S. Money.

Body Code:

<script>
function FormatCurrency(num) { 
var sign, cents; 
num = num.toString().replace(/$|,/g,''); 
if(isNaN(num)) 
num = "0"; 
sign = (num == (num = Math.abs(num))); 
num = Math.floor(num*100+0.50000000001); 
cents = num%100; 
num = Math.floor(num/100).toString(); 
if(cents<10) 
cents = "0" + cents; 
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 + '.' + cents); 
}
/*
 * What follows is to show how to use the function FormatCurrency.
 */
var _A=new Array(-123,123.2312,123456,123456.78)
for(var _i=0;_i<_A.length;_i++)
  document.write("<HR>Convert "+_A[_i]+":<BR><dir>"+FormatCurrency(_A[_i])+"</dir>");
</script>

Times Viewed: 1

Leave a Reply

Your email address will not be published. Required fields are marked *