If you can follow this use of code originally by mwinter of these forums, you can use the .toCurrency() method he has constructed as you see fit. Usage:
10.toCurrency('$')
returns:
$0.10
The only tricky part is that the variable or value used with it must be a number, not a string. That is what the test is about in the below:
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>Simple Currency Demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
// .toCurrency() courtesy of mwinter
// http://www.dynamicdrive.com/forums/s...71&postcount=4
// (http://www.dynamicdrive.com/forums/showpost.php?p=13971&postcount=4)
// leave this credit intact
Number.prototype.toCurrency = function(c, t, d) {
// c=currency symbol (ie:$), t=thousands delimiter (ie:,), d=decimal place delimiter (ie:.)
var n = +this,
s = (0 > n) ? '-' : '',
m = String(Math.round(Math.abs(n))),
i = '',
j, f;
c = c || ''; // you can set the default delimiters here
t = t || '';
d = d || '.';
while (m.length < 3) {m = '0' + m;}
f = m.substring((j = m.length - 2));
while (j > 3) {i = t + m.substring(j - 3, j) + i; j -= 3;}
i = m.substring(0, j) + i;
return s + c + i + d + f;
};
</script>
</head>
<body>
<form>
<input type="text">
<input type="button" title="click to convert number to currency" onclick="if (!isNaN(this.form[0].value*1)){this.form[0].value=(this.form[0].value*1).toCurrency('$')}else{alert('Raw Numbers Only Please!')};">
</form>
</body>
</html>
Bookmarks