PHP4lite PHP4lite - 5 months ago 20
jQuery Question

get 2 decimal numbers with auto round off

How to get 2 decimal numbers with auto round off to my auto total amount fields

.val()
function in jQuery.

heres my code

<script type="text/javascript">
$(document).ready(function(){
$('#AmountPaid, #OtherCharges, #Amount').on('input',function() {
var AmountPaid = parseFloat($('#AmountPaid').val()).toFixed(2);
var OtherCharges = parseFloat($('#OtherCharges').val()).toFixed(2);
var Amount = $('#Amount').val(parseFloat(AmountPaid) + parseFloat(OtherCharges));

});
});
</script>


I have



AmountPaid = 63.48
OtherCharges= 10
Amount =
73.4799999999999



total should be = 73.48

Answer

I use this trick: multiply the number by 100 and then use javascript's round to get it to an interger, then divide by 100.

var Amount =   $('#Amount').val(Math.round((parseFloat(AmountPaid) + parseFloat(OtherCharges)) * 100) / 100).toFixed(2);
Comments