Very interesting, Mike. It ignores the commas that the OP requested but otherwise works very well. I'm wondering how long it will take me to understand what you've done. I'll either learn a lot or give up
Anyways, I got interested in this one and played around with my version a bit more. I've come up with a function that formats dollars and cents with a dollar sign, commas (if appropriate) and two decimal places, with (I believe) iron clad 'error checking' on the input for validity. In the demo below the input field activates the function 'onchange' meaning to see your result appear in the same input field where you entered the raw data, you must click anywhere else on the page:
Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">
<html>
<head>
<title>Format to Dollars and Decimal Cents - Demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript">
function dollarize(tot){
var orig=tot, count=0
var tot=tot.toString().replace(/[,\$]/g, '')
for (var i_tem = 0; i_tem < tot.length; i_tem++){
count=tot.charAt(i_tem)=='.'? count+1 : count
if ((isNaN(tot.charAt(i_tem))&&tot.charAt(i_tem)!=='.')||count>1){
alert('Valid Numbers or Valid Dollar Values only Please')
return orig;
}
}
tot=tot.indexOf('.')==-1? tot+='.0' : tot.length-tot.indexOf('.')==1? tot+='0' : tot
tot=tot.split('.')
tot[2]=''
count=0
tot[0]=parseInt(tot[0], 10).toString()
for (var i_tem = tot[0].length-1 ; i_tem > -1 ; i_tem--){
if (count&&count%3==0)
tot[2]+=','
tot[2]+=tot[0].charAt(i_tem)
count++
}
tot[0]=''
for (var i_tem = tot[2].length-1 ; i_tem > -1 ; i_tem--)
tot[0]+=tot[2].charAt(i_tem)
tot='$'+(tot[0]==''? '0' : tot[0])+'.'+Math.round(Math.abs('.'+tot[1])*100)
tot=tot.length-tot.indexOf('.')==2? tot+='0' : tot
return tot;
}
</script>
</head>
<body>
Enter Dollar amount below:<br>
<input type="text" onchange="this.value=dollarize(this.value)">
</body>
</html>
Bookmarks