【问题标题】:How to round number in javascript if number has 0.04500001 as decimals?如果数字有 0.04500001 作为小数,如何在 javascript 中舍入数字?
【发布时间】:2022-09-27 18:51:18
【问题描述】:

我在一个项目中遇到了这样一个数字:

我想知道在现实世界项目中四舍五入这种数字的情况是什么,以及当它有很多这样的零时如何四舍五入:

 {item.size - item.filled}

我也尝试过toFixed,但它会将其应用于所有生成的数字,因此其他格式与此格式不同的数字也将在小数点后为零。

{(item.size - item.filled).toFixed(7)}

如果是这样,我如何才能只对这种数字进行四舍五入,现实世界项目中的正常情况是什么?我们是否应该不以小数显示所有零?

    标签: javascript reactjs react-native numbers rounding


    【解决方案1】:

    我总是显示两位小数,您的数字是 Javascript 问题。 我使用此函数对其进行舍入:

     export const roundNumberToTwoDecimals = (number) =>
        Math.round(number * 100 + Number.EPSILON) / 100;
    

    【讨论】:

      【解决方案2】:

      在这里,我写了一个格式化各种四舍五入的答案......

      可能与“我想最多舍入两位小数,但仅在必要时”重复。

      <!doctype html>
      <html lang="en">
      <head>
      <meta charset="UTF-8">
      <title>roundPrecision</title>
          <script>
              class MyMath{
                  static roundPrecision(number,precision,fillZeros){
                          // number You want to round
                          // precision nb of decimals
                          // fillZeros the number of 0 You want to add IF necessary!
                          // 0 = no fill with zeros.
                          let num = number;
                          let prec = precision;
                          let exp = Math.pow(10,prec);
                          let round = Math.round(number * exp)/exp
                          if (fillZeros>0){
                              return round.toFixed(fillZeros)
                              }
                          return round;
                      }
              }
          </script>
      </head>
      
      <body>
          <p class="myMath" id="field1"></p>
          <p class="myMath" id="field2"></p>
          <p class="myMath" id="field3"></p>
          <script>
              document.getElementById("field1").innerHTML = MyMath.roundPrecision(5,0,3); // 5.000
              document.getElementById("field2").innerHTML = MyMath.roundPrecision(Math.PI,2,4); // 3.1400
              document.getElementById("field3").innerHTML = MyMath.roundPrecision(2.4,1,2); // 2.40
          </script>
      </body>
      </html>
      
      </head>
      

      【讨论】:

        猜你喜欢
        • 2020-09-25
        • 2022-07-27
        • 1970-01-01
        • 2022-12-03
        • 2010-11-28
        • 1970-01-01
        • 1970-01-01
        • 2022-08-04
        • 2022-07-07
        相关资源
        最近更新 更多