我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
当前回答
+(10).toFixed(2); // = 10
+(10.12345).toFixed(2); // = 10.12
(10).toFixed(2); // = 10.00
(10.12345).toFixed(2); // = 10.12
其他回答
var roundUpto = function(number, upto){
return Number(number.toFixed(upto));
}
roundUpto(0.1464676, 2);
toFixed(2):这里2是我们要舍入的位数。
有一种解决方案适用于所有数字。试试看。表达式如下所示。
Math.round((num + 0.00001) * 100) / 100.
Try Below Ex:
Math.round((1.005 + 0.00001) * 100) / 100
Math.round((1.0049 + 0.00001) * 100) / 100
我最近测试了所有可能的解决方案,并在尝试了近10次后最终得出了结果。
这是计算过程中出现的问题的屏幕截图,
.
转到金额字段。它几乎无限地回归。我尝试了toFixed()方法,但它在某些情况下不起作用(例如,尝试使用pi),最后导出了上面给出的解决方案。
这是astorije的答案的修改版本,更好地支持负值舍入。
// https://stackoverflow.com/a/21323513/384884
// Modified answer from astorije
function round(value, precision) {
// Ensure precision exists
if (typeof precision === "undefined" || +precision === 0) {
// Just do a regular Math.round
return Math.round(value);
}
// Convert the value and precision variables both to numbers
value = +value;
precision = +precision;
// Ensure the value is a number and that precision is usable
if (isNaN(value) || !(typeof precision === "number" && precision % 1 === 0)) {
// Return NaN
return NaN;
}
// Get the sign of value
var signValue = Math.sign(value);
// Get the absolute value of value
value = Math.abs(value);
// Shift
value = value.toString().split("e");
value = Math.round(+(value[0] + "e" + (value[1] ? (+value[1] + precision) : precision)));
// Shift back
value = value.toString().split("e");
value = +(value[0] + "e" + (value[1] ? (+value[1] - precision) : -precision));
// Apply the sign
value = value * signValue;
// Return rounded value
return value;
}
这个函数对我有用。你只需输入数字和你想要舍入的位置,它就可以轻松地完成所需的操作。
round(source, n) {
let places = Math.pow(10, n);
return Math.round(source * places) / places;
}
这对我(TypeScript)起到了作用:
round(decimal: number, decimalPoints: number): number{
let roundedValue = Math.round(decimal * Math.pow(10, decimalPoints)) / Math.pow(10, decimalPoints);
console.log(`Rounded ${decimal} to ${roundedValue}`);
return roundedValue;
}
样本输出
Rounded 18.339840000000436 to 18.34
Rounded 52.48283999999984 to 52.48
Rounded 57.24612000000036 to 57.25
Rounded 23.068320000000142 to 23.07
Rounded 7.792980000000398 to 7.79
Rounded 31.54157999999981 to 31.54
Rounded 36.79686000000004 to 36.8
Rounded 34.723080000000124 to 34.72
Rounded 8.4375 to 8.44
Rounded 15.666960000000074 to 15.67
Rounded 29.531279999999924 to 29.53
Rounded 8.277420000000006 to 8.28