Javascript 小数点后两位不工作

Javascript end to 2 decimals not working

我正在尝试将 2 个字段的输出值设置为 2 个小数。
我试过这样做: .toFixed(2) 但它对我不起作用。我试过这样做:

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;
  }

如果字段以带 2 位小数的数字结尾(例如:3,45),则它工作正常。
但如果以 0 结尾,则不会显示 0。

我认为这应该不是什么大事,但我现在只是尝试了半天...

提前致谢!

当您使用 parseInt() 时,您会得到小数点后的数字,请尝试这样做:

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

parseFloat 将输入中的字符串(这是必要的,因为输入值是字符串)转换为浮点数,然后除以 100 并对结果调用 .toFixed(2)

您可以使用 unary plus +.

将字符串转换为数字
document.getElementById('btw').value = (+total * +btw / 100).toFixed(2);

如果您使用 parseInt,您可能会失去精度。

您可以使用 parseFloat 来实现

var total =65633;
var btw  = 12;

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

您的问题是您 运行 toFixed() 处理字符串,而 toFixed() 只处理数字。

但是您可以这样做:

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

这需要两个数字并进行所有数学运算。然后将其转换为带有两个尾随小数的字符串

在这里查看我的 fiddle:https://jsfiddle.net/6vtrjmax/

确保在整个操作过程中调用 toFixed,即 document.getElementById("btw").value = (parseInt(total) * parseInt(btw) / 100).toFixed(2);

尝试运行下面的代码片段:

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">