0

I'm using JavaScript to display a $ total as checkboxes are checked. It looks like a value of 3.5 is supported, and will display as such. However, 4.0 just returns as 4. I'd like to have it show the decimal places, as a dollar amount.

I'm using the following code:

<input value="4.0" type="checkbox" class="sum" data-toggle="checkbox" name="item1">
<input value="3.5" type="checkbox" class="sum" data-toggle="checkbox" name="item2">
var inputs = document.getElementsByClassName('sum'),
            total  = document.getElementById('order-total');

        for (var i=0; i < inputs.length; i++) {
            inputs[i].onchange = function() {
                var add = this.value * (this.checked ? 1 : -1);
                total.innerHTML = parseFloat(total.innerHTML) + add
                total1.innerHTML = parseFloat(total1.innerHTML) + add
            }
        }

And this is where it will display:

<div class="total-box" style="color: #ffffff;">Total: $<span id="order-total">0</span></div>

It technically works... If a person orders a $4 item, it simply displays $4. If a person adds an item that is $3.50 to it, it displays as $7.50. BUT, if someone only orders the $3.50 item, it shows as $3.5. If I change the code to below:

<div class="total-box" style="color: #ffffff;">Total: $<span id="order-total">0</span>0</div>

$3.50 works perfectly. However, the $4 item displays as $40.

  • 2
    Possible duplicate of [Formatting a number with exactly two decimals in JavaScript](https://stackoverflow.com/questions/1726630/formatting-a-number-with-exactly-two-decimals-in-javascript) – DocMax Oct 17 '17 at 16:03
  • 2
    Possible duplicate of [How can I format numbers as dollars currency string in JavaScript?](https://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-dollars-currency-string-in-javascript) – corsiKa Oct 17 '17 at 16:03

1 Answers1

0

You may want to use Number.toFixed()

eavichay
  • 507
  • 2
  • 7
  • I've been looking into the .toFixed() info, and it looks like I declare the numbers as variables? Example: var num = 5.56789; var n = num.toFixed(2); I'm not declaring any numbers as variables, as they are all added in the inputs directly. I've tried adding the .toFixed in the code where I think it should, but then nothing works. –  Oct 17 '17 at 17:40