如何在Javascript中舍入一个数字?

问题描述 投票:151回答:9

我想使用Javascript来舍入一个数字。由于这个数字是货币,我希望它像这些例子一样向上舍入(2个小数点):

  • 192.168 => 192.20
  • 192.11 => 192.20
  • 192.21 => 192.30
  • 192.26 => 192.30
  • 192.20 => 192.20

如何使用Javascript实现这一目标?内置的Javascript函数将根据标准逻辑(小于和大于5)向上舍入数字。

javascript rounding
9个回答
288
投票
/**
 * @param num The number to round
 * @param precision The number of decimal places to preserve
 */
function roundUp(num, precision) {
  precision = Math.pow(10, precision)
  return Math.ceil(num * precision) / precision
}

roundUp(192.168, 1) //=> 192.2

26
投票

稍晚但是,可以为此创建一个可重用的javascript函数:

// Arguments: number to round, number of decimal places
function roundNumber(rnum, rlength) { 
    var newnumber = Math.round(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength);
    return newnumber;
}

将该功能称为

alert(roundNumber(192.168,2));

18
投票

正常舍入将适用于小调整:

Math.round(price * 10)/10

如果您想保留货币格式,可以使用数字方法.toFixed()

(Math.round(price * 10)/10).toFixed(2)

虽然这会使它成为一个String =)


9
投票

非常接近TheEye的答案,但我改变了一点让它工作:

var num = 192.16;
    
console.log(    Math.ceil(num * 10) / 10    );

2
投票

OP期望两件事: A.舍入到更高的十分之一,和 B.在百分之一的地方显示零(典型的货币需求)。

满足这两个要求似乎需要为上述每个方法采用单独的方法。这是一种建立在suryakiran建议答案的基础上的方法:

//Arguments: number to round, number of decimal places.

function roundPrice(rnum, rlength) {
    var newnumber = Math.ceil(rnum * Math.pow(10, rlength-1)) / Math.pow(10, rlength-1);
    var toTenths = newnumber.toFixed(rlength);
    return toTenths;
}

alert(roundPrice(678.91011,2)); // returns 679.00
alert(roundPrice(876.54321,2)); // returns 876.60

重要提示:此解决方案会产生一个非常不同的结果,包括负数和指数。

为了比较这个答案和两个非常相似的答案,请参阅以下两种方法。第一个简单地舍入到最接近的百分之一,而第二个简单地向上舍入到最接近的百分之一(更大)。

function roundNumber(rnum, rlength) { 
    var newnumber = Math.round(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength);
    return newnumber;
}

alert(roundNumber(678.91011,2)); // returns 678.91

function ceilNumber(rnum, rlength) { 
    var newnumber = Math.ceil(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength);
    return newnumber;
}

alert(ceilNumber(678.91011,2)); // returns 678.92

2
投票

好的,这已经回答了,但我想你可能希望看到我的回答调用math.pow()函数一次。我想我喜欢保持干燥。

function roundIt(num, precision) {
    var rounder = Math.pow(10, precision);
    return (Math.round(num * rounder) / rounder).toFixed(precision)
};

有点把它放在一起。用Math.ceil()替换Math.round()以进行舍入而不是舍入,这是OP想要的。


1
投票

此函数限制小数而不是舍入数

function limitDecimal(num,decimal){
     return num.toString().substring(0, num.toString().indexOf('.')) + (num.toString().substr(num.toString().indexOf('.'), decimal+1));
}

1
投票

我已经使用@AndrewMarshall答案了很长时间,但发现了一些边缘情况。以下测试未通过:

equals(roundUp(9.69545, 4), 9.6955);
equals(roundUp(37.760000000000005, 4), 37.76);
equals(roundUp(5.83333333, 4), 5.8333);

以下是我现在使用的正确行为:

// Closure
(function() {
  /**
   * Decimal adjustment of a number.
   *
   * @param {String}  type  The type of adjustment.
   * @param {Number}  value The number.
   * @param {Integer} exp   The exponent (the 10 logarithm of the adjustment base).
   * @returns {Number} The adjusted value.
   */
  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;
    }
    // If the value is negative...
    if (value < 0) {
      return -decimalAdjust(type, -value, exp);
    }
    // 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));
  }

  // Decimal round
  if (!Math.round10) {
    Math.round10 = function(value, exp) {
      return decimalAdjust('round', value, exp);
    };
  }
  // Decimal floor
  if (!Math.floor10) {
    Math.floor10 = function(value, exp) {
      return decimalAdjust('floor', value, exp);
    };
  }
  // Decimal ceil
  if (!Math.ceil10) {
    Math.ceil10 = function(value, exp) {
      return decimalAdjust('ceil', value, exp);
    };
  }
})();

// Round
Math.round10(55.55, -1);   // 55.6
Math.round10(55.549, -1);  // 55.5
Math.round10(55, 1);       // 60
Math.round10(54.9, 1);     // 50
Math.round10(-55.55, -1);  // -55.5
Math.round10(-55.551, -1); // -55.6
Math.round10(-55, 1);      // -50
Math.round10(-55.1, 1);    // -60
Math.round10(1.005, -2);   // 1.01 -- compare this with Math.round(1.005*100)/100 above
Math.round10(-1.005, -2);  // -1.01
// Floor
Math.floor10(55.59, -1);   // 55.5
Math.floor10(59, 1);       // 50
Math.floor10(-55.51, -1);  // -55.6
Math.floor10(-51, 1);      // -60
// Ceil
Math.ceil10(55.51, -1);    // 55.6
Math.ceil10(51, 1);        // 60
Math.ceil10(-55.59, -1);   // -55.5
Math.ceil10(-59, 1);       // -50

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


0
投票

parseInt总是向下舍入......

console.log(parseInt(5.8)+1);

做parseInt()+ 1

© www.soinside.com 2019 - 2024. All rights reserved.