Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Round to 2 decimal places and calculate with that number

How to round the tax and brutto values to 2 decimal places...

I have tried to use .toFixed(2) but that returns a string and then i can't calculate with it anymore.

If someone could update the fiddle and make it work please?

And try to input number 23

DEMO Fiddle

// calculate brutto and tax
$(document).on('keyup paste', '#netto', function () {

  var netto = $("#netto").val();
  $("#brutto").val(netto * 1.19).toFixed(2);
  var brutto = $("#brutto").val();
  $("#tax").val(brutto - netto);

});
like image 318
lewis4u Avatar asked Dec 11 '22 13:12

lewis4u


1 Answers

Few issues in your code:

1) You don't need event delegation unless you have elements being loaded dynamically.

2) you should always parse values before doing any mathematical operations on them.

3) you are using .toFixed(2) on jquery method which is throwing the error. toFixed should be used with float values instead. also make sure that toFixed is used while setting both textbox values:

// calculate brutto and tax
$('#netto').on('keyup paste', function () {
  var netto = parseFloat($("#netto").val());
  $("#brutto").val((netto * 1.19).toFixed(2));
  var brutto =  parseFloat($("#brutto").val());
  $("#tax").val((brutto - netto).toFixed(2));
});

Working Demo

like image 126
Milind Anantwar Avatar answered Feb 22 '23 22:02

Milind Anantwar