1

I have some javascript code that caluclates sales tax on a web form and totals everything up. I am setting the number to decimals using toFixed(2) and adding the calculated tax to my subtotal using basic addition. The end result is off by 1 cent. My subtotal and tax amount field show the correct amount but my total field does not.

As a workaround, I changed my subtotal calculation to .toFixed(3), but am curios how I can correctly get this to calculate and display properly with 2 decimals. I am not that good with javascript so am stumped on this.

Here is my javascript (Not showing everything, just the relevant code):

var taxper = document.autoSumForm.taxRate.value*1.0;
tax = subtotal*(taxper/100).toFixed(3); 
document.autoSumForm.subtotal.value = subtotal.toFixed(2);
document.autoSumForm.tax.value = tax.toFixed(3);

And here is an example calculation:

Taxper = 6.625%
Subtotal = $20.00
Tax = 6.625% * $20.00
Tax amount = 1.32
Total = $21.32 <---- This displays $21.33 if I don't set subtotal calculation to toFixed(3)
Brian Fleishman
  • 1,237
  • 3
  • 21
  • 43
  • 2
    JavaScript numbers are *binary floating-point* values; doing "money math" with binary floating-point is a fundamentally bad idea. The `.toFixed()` function returns a *string*, not a number, and as soon as you start doing more math you're basically back where you started from. – Pointy Aug 06 '19 at 16:59
  • Please edit your post to put the title in the form of a question, it is not clear what you are asking. – stackuser83 Aug 06 '19 at 17:02
  • Why is rounding up with two decimal places an issue? The value 1.325 *should* be rounded up to 1.33, if I am understanding correctly. – StardustGogeta Aug 06 '19 at 17:03
  • Yes, you're right. I didn't realize that sales tax always rounds up. I will edit my post. – Brian Fleishman Aug 06 '19 at 17:07

0 Answers0