如何在Javascript中求整数?

如何在Javascript中求整数?,javascript,rounding,Javascript,Rounding,我想用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以进行取整)。正常取整将通过一个小的调整进行: Math.round(price * 10)/10 如果您想保留货币格式

我想用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以进行取整)。

正常取整将通过一个小的调整进行:

Math.round(price * 10)/10
如果您想保留货币格式,可以使用Number方法
.toFixed()

虽然这将使它成为一个字符串=)

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

var num=192.16;

console.log(Math.ceil(num*10)/10)稍晚,但可以为此创建一个可重用的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));

此函数用于限制无整数的十进制数

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

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
重要提示:此解决方案会产生非常不同的负数和指数结果

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


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

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

它把所有的东西都放在一起了。将Math.round()替换为Math.ceil()以进行取整,而不是取整,这是OP想要的。

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

equals(roundUp(9.69545, 4), 9.6955);
equals(roundUp(37.760000000000005, 4), 37.76);
equals(roundUp(5.83333333, 4), 5.8333);
下面是我现在用来让round up正确操作的方法:

// 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
//闭包
(功能(){
/**
*数字的十进制调整。
*
*@param{String}type调整的类型。
*@param{Number}值该数字。
*@param{Integer}exp指数(调整基数的10对数)。
*@返回调整后的值{Number}。
*/
函数decimalAdjust(类型、值、exp){
//如果exp未定义或为零。。。
if(typeof exp==‘未定义’| |+exp===0){
返回数学[类型](值);
}
值=+值;
exp=+exp;
//如果值不是数字或exp不是整数。。。
如果(isNaN(值)| |!(typeof exp=='number'&exp%1==0)){
返回NaN;
}
//如果值为负。。。
如果(值<0){
return-decimalAdjust(type,-value,exp);
}
//移位
value=value.toString().split('e');
value=Math[type](+(值[0]+'e'+(值[1]?(+value[1]-exp):-exp));
//向后移动
value=value.toString().split('e');
返回+(值[0]+'e'+(值[1]?(+value[1]+exp):exp));
}
//小数点
如果(!Math.round10){
Math.round10=函数(值,exp){
返回十进制调整('round',value,exp);
};
}
//十进制楼层
如果(!数学地板10){
Math.floor10=函数(值,exp){
返回十进制调整('floor',value,exp);
};
}
//十进制ceil
如果(!Math.ceil10){
Math.ceil10=函数(值,exp){
返回decimalAdjust('ceil',value,exp);
};
}
})();
//圆的
数学圆10(55.55,-1);//55.6
数学圆10(55.549,-1);//55.5
数学圆10(55,1);//60
数学圆10(54.9,1);//50
数学圆10(-55.55,-1);//-55.5
数学圆10(-55.551,-1);//-55.6
数学圆10(-55,1);//-50
数学圆10(-55.1,1);//-60
数学圆10(1.005,-2);//1.01——将其与上面的数学四舍五入(1.005*100)/100进行比较
数学圆10(-1.005,-2);//-1.01
//地板
数学地板10(55.59,-1);//55.5
数学10(59,1);//50
数学地板10(-55.51,-1);//-55.6
数学地板10(-51,1);//-60
//细胞
数学10(55.51,-1);//55.6
数学。ceil10(51,1);//60
数学ceil10(-55.59,-1);//-55.5
数学。ceil10(-59,1);//-50

来源:

parseInt总是将soo四舍五入


console.log(parseInt(5.8)+1)
Math.round(192.11*100)/100->192.11第二个不需要舍入,它更像是
price.toFixed(2)
@Krtek ooops,谢谢你的关注。我看错了问题。答案已更新。OP询问如何对一个数字进行取整,因此这里应该使用Math.ceil而不是Math.round。@AndrewMarshall乘法的目的是什么,然后除以10?@codecowboy如果不这样做,则
ceil()
将给出
193
,因此,我们必须确保我们想要保持的所有精度都在小数点之前。然后我们做逆运算以恢复“原始”值。如果你得到一些像
192.19999999997
,你可以将
.toFixed(1)
应用到
num
上,对于那些想知道如何取整到最接近的整数的人,你只需要Math.ceil()。剩下的只是处理小数。为了节省别人的时间,我的大脑花了这么多时间!注意这个函数不是完全准确的!综述(1.09,2)返回1.1,这是错误的!预期的答案仍然是1.09。作为较短的替代选项:return(''+num).split('..).shift()感谢Roberto完成了这段代码,但删除了所有的小数。这很好,但OP询问了如何对数字进行取整,所以这里应该使用Math.ceil,而不是Math.round。如果您希望正确地进行四舍五入,那么这个答案比公认的答案要好,不管小数点是哪一位
function roundIt(num, precision) {
    var rounder = Math.pow(10, precision);
    return (Math.round(num * rounder) / rounder).toFixed(precision)
};
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