【问题标题】:html output 2 digitshtml输出2位数
【发布时间】:2013-10-07 08:47:13
【问题描述】:

我想要一个简单的计算表格。 我以 w3schools 为例:

这是经过 myd 调整的代码:

<!DOCTYPE html>
<html>
<body>

<form oninput="x.value=parseFloat(a.value).round(2)* parseFloat(b.value).round(2)">
<input type="number" id="a" value="50">
+<input type="number" id="b" value="50">
=<output name="x" for="a b"></output>
</form>

<p><strong>Note:</strong> The output tag is not supported in Internet Explorer.</p>

</body>
</html>

当我添加回合(2)(输入形式)时,它将不起作用。 如果我删除它,它会工作。但如果我在小数点后添加一些数字,我会得到一大堆数字,其中有很多零。

我只想要一个 2 位数的输出。

谁能帮帮我?

我也查看了这个链接:

parse float with two decimal places

但我无法让它工作

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    假设您将 0.11 和 0.12 相乘 - 这两个数字都有两位小数。结果是 0.132,有 3 个。这是假设您使用可以准确表示的数字:大多数十进制数字不能。

    您应该对输出进行四舍五入,而不是四舍五入:

    x.value = (a.value*b.value).round(2);
    

    话虽如此,我不认为round 是一个可以这样使用的函数。我认为你需要这样做:

    x.value = Math.round(a.value*b.value*100)/100;
    

    请注意,由于* 自动将其参数转换为数字(与+ 不同),因此无需显式parseFloat

    【讨论】:

      猜你喜欢
      • 2020-08-13
      • 1970-01-01
      • 2013-01-29
      • 1970-01-01
      • 2014-02-28
      • 2019-04-01
      • 1970-01-01
      • 2016-08-12
      • 1970-01-01
      相关资源
      最近更新 更多