Javascript end to 2 decimals not working

93 Views Asked by At

i'm trying to set an output value from 2 fields to 2 decimals.
i've tried doing this with: .toFixed(2) but it didn't work for me. I tried doing this:

calculate = function () {
      var total = document.getElementById('totaal').value;
      var btw = document.getElementById('percentage').value;
      document.getElementById('btw').value = parseInt(total.toFixed(2)) * parseInt(btw.toFixed(2)) / 100;
  }

If the field ends on a number with 2 decimals (for example: 3,45) it is working correctly.
But if it ends with a 0, it does not show the 0.

I think this shoudn't be this mutch of a deal but i'm just trying for half a day now...

Thanks in advance!

5

There are 5 best solutions below

0
On BEST ANSWER

When you use parseInt() you then get the numbers after the decimal points removed, try doing this :

document.getElementById('btw').value = (parseFloat(total) * parseFloat(btw) / 100).toFixed(2);

parseFloat converts the string (and it's necessary because input values are string) in the input to a float, then divide by 100 and call .toFixed(2) on the result.

0
On

You could convert a string to number by using an unary plus +.

document.getElementById('btw').value = (+total * +btw / 100).toFixed(2);

If you use parseInt, you loose precision, which you may have.

0
On

You can use parseFloat to achieve this

var total =65633;
var btw  = 12;

console.log(parseFloat((total* btw)/100).toFixed(2))

0
On

Your issues is that you're running toFixed() on strings, and toFixed() only works on numbers.

You could however, do this:

document.getElementById('btw').value = 
        (parseInt(total) * parseInt(btw) / 100).toFixed(2)

This takes the two numbers and does all the math. It then converts it to a string with two trailing decimals

See my fiddle here: https://jsfiddle.net/6vtrjmax/

0
On

Make sure you are calling toFixed on the entire operation i.e. document.getElementById("btw").value = (parseInt(total) * parseInt(btw) / 100).toFixed(2);

Try running the snippet below:

calculate = function() {
  var total = document.getElementById("total").value;
  var btw = document.getElementById("percentage").value;
  if (total && btw) {
    document.getElementById("btw").value = 
      (parseInt(total) * parseInt(btw) / 100).toFixed(2);
  }
};
<input onchange="calculate()" placeholder='total' type="decimal" id="total">
<input onchange="calculate()" placeholder='percentage' type="decimal" id="percentage">
<input type="decimal" placeholder='result' id="btw">