Reputation: 73
I have a form that caculates the sum of amounts entered. I wanted to know how I can make the output go from somthing like:
97.231345
to
97.23
I'm trying to use US currency formatting but without the dollar sign, while being able to round off to the nearest hundredth if that's even possible. I apologize for my lack of knowledge and give thanks in advance for all your help. I really do appreciate your time, thanks.
<script type="text/javascript">
function addition(){
a=Number(document.calculator.number1.value);
b=Number(document.calculator.number2.value);
c=a+b;
document.calculator.total.value=c;
}
</script>
<br/>
<form name="calculator">
Enter Product Price(s) HERE
Product A: $ <input name="number1" size="9" type="text"><br>
Product B: $ <input name="number2" size="9" type="text"><br>
TOTAL: $<input name="total" size="14" type="text"><br>
<input onClick="javascript:addition();" value="UPDATE" type="button">
</form>
Upvotes: 0
Views: 185
Reputation: 20151
function nearestCent(amt) {
return Math.round(amt*100)/100;
}
function displayNearestCent(amt) {
var dollars = Math.floor(amt);
return dollars + "." + Math.round((amt-dollars)*100);
}
c = nearestCent(a + b);
document.calculator.total.value = displayNearestCent(c);
There are two issues to be aware of. The first is the one you've seen, that storing amounts as floats can lead to 0.33333 type problems. The second is that even if you round to cents, javascript's binary representation of your fraction will not be exact for every number of cents, so you'll need rounding to produce the display string as well.
The real solution is to use integer numbers of cents:
function nearestCents(amt) {
return Math.round(amt * 100);
}
function displayCentsInDollars(cents) {
var dollars = Math.floor(cents/100);
return dollars + "." + Math.round(cents - 100*dollars);
}
That way once you have converted the amounts to cents, you are just using whole numbers of cents.
Upvotes: 0