PDA

View Full Version : Need formatting help on results of form



Robot1
12-03-2005, 03:52 AM
This is my 2nd javascript. I have gotten the code to work correctly. I would like to have the 3 output fields formatted as currency, with two decimal places. What would be the best way to do that?


<SCRIPT LANGUAGE="JavaScript">
<!--begin script
function compute(form) {
var mch = parseInt(form.minschange.value);
var mv = parseInt(form.minsverify.value);
var mcl = parseInt(form.minsclean.value);
var person = parseInt(form.person.value);
var hard = parseInt(form.hardware.value);
var tps = parseInt(form.tapes.value);
var inhouse = (((((mch + mv + mcl) *260) /60) *person) +hard +tps);
var pdsservice = (form.storage.value *12);
inhouse = twoDecs(inhouse);
pdsservice = twoDecs(pdsservice);
form.inhouse.value = inhouse;
form.pdsservice.value = pdsservice;
var savings = (form.inhouse.value -form.pdsservice.value);
savings = twoDecs(savings);
form.savings.value = savings;
}
function twoDecs(item) {
return eval(parseInt(item *100) *.01);
}
// End -->
</script>

jscheuer1
12-03-2005, 06:56 AM
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:


<!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/showpost.php?p=13971&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>