0

Can any one help me with this, I'm trying to use this code on a POS to calculate the change to give a customer and it works for the must part.

The problem I'm having is if I an order costs £9.99 and I enter £10, instead of it calculating the change as £0.01 it calculates it as £ 0.009999999999999787

Here is the code that I'm using.

function sum() {
    var og_total = document.getElementById('og_cart_total').value;
    var og_tendered = document.getElementById('og_cash_tendered').value;
    var og_change = (og_tendered - og_total).toFixed(2);
    var og_symbol = '£';
    if (!isNaN(og_change)) {
        document.getElementById('og_change_given').value = og_symbol + og_change;
    }
}
<input type="hidden" id="og_cart_total"  value="19.99" onkeyup="sum();" />

<div class="control-group">
<label class="control-label" for="og_cash_tendered">Tendered:</label>
<div class="controls">
 <input class="cm-autocomplete-off" type="text" name="payment_info[og_cash_tendered]" value="" id="og_cash_tendered" onkeyup="sum();" />
</div>
</div>

<div class="control-group">
<label class="control-label" for="og_change_given">Change:</label>
<div class="controls">
 <input type="text" name="payment_info[og_change_given]" id="og_change_given" value="£-19.99" readonly="readonly" />
</div>
</div>

1 Answers1

0

there is this way but it's not as promising as it should. the best way is to use a library for long numbers if it worth the trouble.

function sum() {
            var og_total = document.getElementById('txt1').value;
            var og_tendered = document.getElementById('txt2').value;
            var og_change = (og_tendered - og_total).toFixed(2);
            var og_symbol = "£";
            if (!isNaN(og_change)) {
                document.getElementById('og_change_text').value = og_symbol + og_change;
            }
        }
<input type="text" id="txt1"  value="9.99" readonly="readonly" onkeyup="sum();" />
<input type="text" id="txt2"  onkeyup="sum();" />
<input type="text" readonly="readonly" id="og_change_text" />
The Moisrex
  • 1,857
  • 1
  • 14
  • 16