首页 > 解决方案 > 使用 html 和 javascript 将结果四舍五入到小数点后 2 位

问题描述

   <script>
     function e(element)
     {
        return document.getElementById(element);
     }

     function f(element)
     {
        return parseFloat(e(element).value);
     }

     function updateResult()
     {

        e("inputK").value = f("inputG")*1.33* (f("inputI")/(f("inputH")+ f("inputI")))
     }

  </script>

对于上面显示的代码,我请求帮助将值四舍五入到小数点后 2 位

结果-- input type="text" id="inputK" readonly="true" 我试过 math.round(inputK) 它不起作用你的建议将帮助我改善结果。

标签: htmlmath

解决方案


正如您所提到的,您正在使用仅返回整数的Math.round() 。有多种方法可以实现目标。

  1. Math.round(num * 100) / 100-- 返回数字
  2. var numb = 123.23454; numb = numb.toFixed(2); -- 返回字符串
  3. Math.round(num + "e+2") + "e-2"-- 返回数字
  4. Number.prototype.round = function(places) { return +(Math.round(this + "e+" + places) + "e-" + places); }-- 返回数字

推荐阅读