Javascript 如何在Javascript中四舍五入一个数字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5191088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to round up a number in Javascript?
提问by cyberfly
I want to use Javascript to round up a number. Since the number is currency, I want it to round up like in these examples (2 decimal points):
我想使用 Javascript 来四舍五入一个数字。由于数字是货币,我希望它像这些示例中那样四舍五入(2 个小数点):
- 192.168 => 192.20
- 192.11 => 192.20
- 192.21 => 192.30
- 192.26 => 192.30
- 192.20 => 192.20
- 192.168 => 192.20
- 192.11 => 192.20
- 192.21 => 192.30
- 192.26 => 192.30
- 192.20 => 192.20
How to achieve this using Javascript? The built-in Javascript function will round up the number based on standard logic (less and more than 5 to round up).
如何使用 Javascript 实现这一目标?内置的 Javascript 函数将根据标准逻辑对数字进行四舍五入(小于和大于 5 进行四舍五入)。
回答by Andrew Marshall
/**
* @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
回答by suryakiran
Little late but, can create a reusable javascript function for this purpose:
有点晚了,但是可以为此创建一个可重用的 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;
}
Call the function as
调用函数为
alert(roundNumber(192.168,2));
回答by Shad
Normal rounding will work with a small tweak:
正常四舍五入只需稍作调整即可:
Math.round(price * 10)/10
and if you want to keep a currency format, you can use the Number method .toFixed()
如果要保留货币格式,可以使用 Number 方法 .toFixed()
(Math.round(price * 10)/10).toFixed(2)
Though this will make it a String =)
虽然这将使它成为一个字符串 =)
回答by Hoàng Long
Very near to TheEyeanswer, but I change a little thing to make it work:
非常接近TheEye 的答案,但我更改了一些小东西以使其工作:
var num = 192.16;
console.log( Math.ceil(num * 10) / 10 );
回答by Kay V
The OP expects two things:
A. to round up to the higher tenths, and
B. to show a zero in the hundredths place (a typical need with currency).
OP 期望两件事:
A. 向上取整到较高的十分之一,
B. 在百分之一位置显示零(货币的典型需求)。
Meeting both requirement would seem to necessitate a separate method for each of the above. Here's an approach that builds on suryakiran's suggested answer:
满足这两个要求似乎需要针对上述每个要求单独的方法。这是一种基于 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
Important note: this solution produces a very different result with negative and exponential numbers.
重要提示:此解决方案会产生非常不同的结果,带有负数和指数数。
For the sake of comparison between this answer and two that are very similar, see the following 2 approaches. The first simply rounds to the nearest hundredth per usual, and the second simply rounds up to the nearest hundredth (larger).
为了将此答案与两个非常相似的答案进行比较,请参阅以下两种方法。第一个简单地四舍五入到最接近的百分之一,第二个简单地四舍五入到最近的百分之一(更大)。
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
回答by John Grabauskas
ok, this has been answered, but I thought you might like to see my answer that calls the math.pow() function once. I guess I like keeping things DRY.
好的,这已得到解答,但我想您可能希望看到我调用 math.pow() 函数一次的答案。我想我喜欢保持干燥。
function roundIt(num, precision) {
var rounder = Math.pow(10, precision);
return (Math.round(num * rounder) / rounder).toFixed(precision)
};
It kind of puts it all together. Replace Math.round() with Math.ceil() to round-up instead of rounding-off, which is what the OP wanted.
它有点把它放在一起。将 Math.round() 替换为 Math.ceil() 以进行四舍五入而不是四舍五入,这正是 OP 想要的。
回答by Behnam Mohammadi
this function limit decimal without round number
此功能限制没有舍入数的小数
function limitDecimal(num,decimal){
return num.toString().substring(0, num.toString().indexOf('.')) + (num.toString().substr(num.toString().indexOf('.'), decimal+1));
}
回答by Nicolas BADIA
I've been using @AndrewMarshall answer for a long time, but found some edge cases. The following tests doesn't pass:
我一直在使用@AndrewMarshall 的答案,但发现了一些边缘情况。以下测试未通过:
equals(roundUp(9.69545, 4), 9.6955);
equals(roundUp(37.760000000000005, 4), 37.76);
equals(roundUp(5.83333333, 4), 5.8333);
Here is what I now use to have round up behave correctly:
这是我现在用来正确进行围捕的方法:
// 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
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
来源:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
回答by Omar
parseInt always rounds down soo.....
parseInt 总是四舍五入.....
console.log(parseInt(5.8)+1);
do parseInt()+1
做 parseInt()+1