【问题标题】:I can't round it on 2 decimals我不能把它四舍五入到小数点后两位
【发布时间】:2016-01-25 10:47:03
【问题描述】:

我正在尝试将此脚本的结果给出小数点后 2 位。它们实际上都已经有 2 位小数,但是当我将最后 2 位加在一起 ​​(35.75 + 16.06) 时,我得到 €51.629999999999995 作为输出。

这是我的脚本;

<!DOCTYPE html>

<html>
  <head>
    <script>
      function bereken() {
        var total = 0;
        if (document.forms[0].boek1.checked)  {
          total += 27.74;
        }
        if (document.forms[0].boek2.checked) {
          total += 26.13;
        }
        if (document.forms[0].boek3.checked) {
          total += 35.57;
        }
        if (document.forms[0].boek4.checked) {
          total += 16.06;
        }
        totalP = "€" + total
        document.forms[0].total.value = totalP; 
      } 
    </script>

  </head>

  <body>
    <form>
      <input type="checkbox" name="boek1">Boek 1<br>
      <input type="checkbox" name="boek2">Boek 2<br>
      <input type="checkbox" name="boek3">Boek 3<br>
      <input type="checkbox" name="boek4">Boek 4<br>
      <div><input type="button" value="Totaal" onclick="bereken()" /><br><br>
        <input type="text" value="€" name="total" size="5" />
    </form>
  </body>

你们有谁知道我做错了什么吗?

【问题讨论】:

标签: javascript numbers decimal


【解决方案1】:

使用Math.round():

document.forms[0].total.value = Math.round(parseFloat(totalP.substr(1)) * 100)/100;

工作预览

还有其他方法可以做到这一点。你也可以使用.toFixed(n)

document.forms[0].total.value = parseFloat(totalP.substr(1)).toFixed(2);

【讨论】:

  • OP 询问 2 位小数
  • @RayonDabre *100/100 会给出两位小数,对吧?我是不是做错了什么?
  • @Praveen,输入是€51.629999999999995
  • 这个怎么样:var input=51.629999999999995; var final=input.toFixed(2); alert(final);
  • @AmirAkbulut 您有任何更新吗?好不好用?
【解决方案2】:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round

检查函数decimalAdjust。效果不错

function decimalAdjust(type, value, exp) {
    // If the exp is undefined or zero...
    if (typeof exp === 'undefined' || +exp === 0) {
      return Math[type](value);
    }
    value = +value;
    exp = +exp;
    // If the value is not a number or the exp is not an integer...
    if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
      return NaN;
    }
    // Shift
    value = value.toString().split('e');
    value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
    // Shift back
    value = value.toString().split('e');
    return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-02
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多