0

A part of my code deals with math and summations. Most of the equations equal out to be three decimals, but I want to fix it at 2. I know to use tofixed(2), but it doesn't seem to matter where I put the function, the numbers remain at three decimals. I'm sure I'm making some stupid mistake

  <script language="JavaScript">

      function SetFoodItems(amount) {
        // returns the amount in the .99 format
        return (amount == Math.floor(amount)) ? amount + '.00' : ((amount * 10 
   == Math.floor(amount * 10)) ? amount + '0' : amount);
      }

      function SelectFoodItems(form) {
        var UpdateCosts = (form.quantity.value - 0) * (form.unitcost.value - 
       0) + (form.quantity1.value - 0) * (form.unitcost1.value - 0) 
       (form.quantity2.value - 0) * (form.unitcost2.value - 0) + 
        (form.quantity3.value - 0) * (form.unitcost3.value - 0).toFixed(2);

        UpdateCosts = Math.floor((subtotal * 1000) / 1000).toFixed(2);
        form.subtotal.value = ('$' + cent(subtotal));

        var tax = (UpdateCosts / 100 * (form.rate.value - 0).toFixed(2);
        tax = Math.floor(tax * 1000) / 1000;
        form.tax.value = '$' + cent(tax);

        total = UpdateCosts + tax;
        total = Math.floor((total * 1000) / 1000);
        form.total.value = ('$' + cent(total)).toFixed(2);
      }



    </script>
Pythos
  • 3
  • 3

2 Answers2

0

That's because toFixed(2) returns a 2 pt decimal in a string like "2.25". You need to parseFloat("2.25") to get 2.25 before proceeding with further operations.

0

Your final line:

form.total.value = ('$' + cent(total)).toFixed(2);

It should be adjusted to:

form.total.value = '$' + cent(total).toFixed(2);

The ('$' + cent(total)) bit converts the total into a string which does not have the toFixed method.

However, toFixed does not round a number, it truncates (chopping off digits, 2.005 will become "2.00" not "2.01") and asserts there will be exactly n digits in a new string. Using the result in further numeric operations can cause issues (adding a number to a string will append).

You can use the Math.round function with multiplication and division to achieve rounding if that is what you're really after.

You can see how to achieve that here: How do you round to 1 decimal place in Javascript?

Or as a function you can use directly in your code:

function roundMoney(dollarAmount) {
    var cents = dollarAmount * 100;
    return Math.round(cents) / 100;
}

When finally displaying the value in form.value.total you will still need toFixed to maintain two decimals at the end