【问题标题】:Round to the next whole number javascript四舍五入到下一个整数javascript
【发布时间】:2020-04-01 13:13:31
【问题描述】:

我想在 JavaScript 中实现类似的东西:

input = 2455.55
f(input) = 2456
f(input) = 2460
f(input) = 2500
f(input) = 3000
f(input) = 2455.55

我现在正在使用Math.round() 方法,但使用它只能达到 2,546。想知道是否有实现其余部分的最佳方法。

【问题讨论】:

  • 您想要的似乎是 (a) 舍入小数点,然后 (b) 舍入每个数字。对吗?
  • 为什么不是2,455.55 -> f(n) -> 2,455.6 -> f(n) -> 2,456
  • 您需要中间步骤还是只想要最后的 3000?

标签: javascript math rounding


【解决方案1】:

您可以将数字除以 10,直到得到一个非整数,然后将其四舍五入,然后再次乘以 10,所用时间相同。像这样的:

    function roundUp(n) {
    
        var n2 = n;
        var i=0;
        while (Number.isInteger(n2)) {
      	    n2 /= 10;
            i++;
        }
        return Math.round(n2) * Math.pow(10, i);
    
    }

    console.log(roundUp(2455.55)); // 2456
    console.log(roundUp(2456)); // 2460
    console.log(roundUp(2460)); // 2500
    console.log(roundUp(2500)); // 3000

【讨论】:

    【解决方案2】:

    根据您想要的输出,您似乎需要跟踪函数调用的数量。这似乎不是您函数的参数。

    鉴于您只有一个参数的限制,实现看起来可能像

    var lastNum = 0
    var digitsToRound = 0
    
    function roundUp(input) {
      // Verify whether the function is called with the same argument as last call.
      // Note that we cannot compare floating point numbers.
      // See https://dev.to/alldanielscott/how-to-compare-numbers-correctly-in-javascript-1l4i
      if (Math.abs(input - lastNum) < Number.EPSILON) {
        // If the number of digitsToRound exceeds the number of digits in the input we want
        // to reset the number of digitsToRound. Otherwise we increase the digitsToRound.
        if (digitsToRound > (Math.log10(input) - 1)) {
          digitsToRound = 0;
        } else {
          digitsToRound = digitsToRound + 1;
        }
      } else {
        // The function was called with a new input, we reset the digitsToRound
        digitsToRound = 0;
        lastNum = input;
      }
    
      // Compute the factor by which we need to divide and multiply to round the input
      // as desired.
      var factor = Math.max(1, Math.pow(10, digitsToRound));
      return Math.ceil(input / factor) * factor;
    }
    
    
    console.log(roundUp(2455.55)); // 2456
    console.log(roundUp(2455.55)); // 2460
    console.log(roundUp(2455.55)); // 2500
    console.log(roundUp(2455.55)); // 3000
    

    【讨论】:

      【解决方案3】:

      谢谢,不错!受您的回答启发,我这样解决了:

      function roundNumber(num, n) {
        const divider = Math.pow(10, n);
        return Math.round(num / divider) * divider;
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-11
        • 1970-01-01
        • 1970-01-01
        • 2010-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多