1

Following is the jQuery code

    $('#Cancelation').change(function(){        
        if($(this).is(':checked')){
            total = parseFloat($('#TotalAmount').val()) + parseFloat($('#Cancelation').val());                      
        } else {
        total = parseFloat($('#TotalAmount').val()) - parseFloat($('#Cancelation').val());
        }
        $('#TotalAmount').val(total);
        $('#TotalPrice').html(total);
    });

If the #TotalAmount value is 10.49 which shows correctly on page load and problem is that if checkbox checked or unchecked, value of checkbox which is 2.00 added or subtract from #TotalAmount and #TotalPrice but the output shows like 12.48999998 on add 0r 10.48999998 on subtract.

I tried .toFixed(2); but the result is same, any other way to fix the issue?

Edited: HTML Code

<label for="Cancelation"><input type="checkbox" name="Cancelation" id="Cancelation" value="2.00"> Cancellation Protection: 2.00</label>
<input type="text" name="TotalAmount" id="TotalAmount" value="10.49" />
Total Amount: <span id="TotalPrice">10.49</span>
Shehary
  • 9,926
  • 10
  • 42
  • 71
  • can you post your html – depperm Jul 13 '15 at 20:45
  • html code added in question. – Shehary Jul 13 '15 at 20:51
  • your code seems to work http://jsfiddle.net/2c9uy9cw/ – depperm Jul 13 '15 at 20:54
  • @depperm agree with you it worked I used same code same way on another site and there its working but the page I'm currently working on its not working as it should be, so any idea or any solution coz i don't see a way to debug a correctly working code – Shehary Jul 13 '15 at 20:57
  • 1
    do you have any other js that affects Cancelation, TotalAmount, or TotalPrice? – depperm Jul 13 '15 at 20:58
  • yes and as you mentioned i deleted all the other js and just keep the code in question just to be sure and checked, the result is same, no change. – Shehary Jul 13 '15 at 21:11

2 Answers2

3

You can use Math.round(number * 100) / 100 to round to two decimal places.

mac
  • 858
  • 1
  • 6
  • 11
3

After little bit research and checking answers at following link

Round to at most 2 decimal places in JavaScript


Sorted the problem with adding java, Thanks to mac who suggested Math.round.

<script>
    var round = Math.round;
    Math.round = function (value, decimals) {
      decimals = decimals || 0;
      return Number(round(value + 'e' + decimals) + 'e-' + decimals);
    }

    $('#Cancelation').change(function(){        
        if($(this).is(':checked')){
            total = parseFloat($('#TotalAmount').val()) + parseFloat($('#Cancelation').val());                      
        } else {
            total = parseFloat($('#TotalAmount').val()) - parseFloat($('#Cancelation').val());
        }
            $("#TotalAmount").val(Math.round(total, 2));
            $("#TotalPrice").html(Math.round(total, 2));
    });
</script>
Community
  • 1
  • 1
Shehary
  • 9,926
  • 10
  • 42
  • 71