Click to See Complete Forum and Search --> : Calculate change
nicoletonyf
06-26-2003, 04:24 PM
Hello there, I'm new to javaScript.
I would like to create a function in order to divide out a number ($9.80) in dollars, quarters, dimes, nickels, and pennies. Each unit will be displayed in a different text box.
Thanks, nic.
Vladdy
06-26-2003, 04:41 PM
function makeChange(amount)
{ this['dollars'] = Math.floor(amount);
amount = amount%1;
this['quarters'] = Math.floor(amount/0.25);
amount = amount%0.25;
this['dimes'] = Math.floor(amount/0.1);
amount = amount%0.1;
this['nickels'] = Math.floor(amount/0.05);
amount = (amount%0.05)*100;
this['pennies'] = Math.floor(amount);
return;
}
Charles
06-26-2003, 04:54 PM
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="Content-Script-Type" content="text/javascript">
<title>Example</title>
<style type="text/css">
<!--
label {display:block; margin:1em 0em}
-->
</style>
<script type="text/javascript">
<!--
function evaluate (amt) {
amt.value = amt.value.match(/[\d\.]/g).join('');
amt.form.dollars.value = Math.floor(amt.value / 1);
amt.form.quarters.value = Math.floor((amt.value % 1) / .25);
amt.form.dimes.value = Math.floor((amt.value % .25) / .10);
amt.form.nickles.value = Math.floor((amt.value % .10) / .5);
amt.form.pennies.value = Math.floor((amt.value % .5) / .1);
}
// -->
</script>
<form action="">
<div>
<label>Ammount<br><input name="ammount" type="text" onchange="evaluate(this)"></label>
<label>Dollars<br><input name="dollars" type="text"></label>
<label>Quarters<br><input name="quarters" type="text"></label>
<label>Dimes<br><input name="dimes" type="text"></label>
<label>Nickles<br><input name="nickles" type="text"></label>
<label>Pennies<br><input name="pennies" type="text"></label>
</form>