我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
当前回答
考虑.toFixed()和.toPrecision():
http://www.javascriptkit.com/javatutors/formatnumber.shtml
其他回答
这是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;
}
2022,原生,无库,现代浏览器,清晰可读。
函数循环(价值最小分数位数,最大分数位数) {const formattedValue=value.toLocaleString('en'{useGrouping:false,最小分数位数,最大分数位数})返回编号(格式化值)}console.log(圆形(21.891,2,3))//21.891console.log(round(1.8,2))//1.8,如果需要1.80,请删除“Number”函数。直接返回“formattedValue”。console.log(圆形(21.0001,0,1))//21console.log(圆形(0.875,3))//0.875
这个答案更关乎速度。
var precalculatedPrecisions = [1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10];
function round(num, _prec) {
_precision = precalculatedPrecisions[_prec]
return Math.round(num * _precision + 1e-14) / _precision ;
}
jsPerf关于这一点。
最简单的方法是使用toFixed,然后使用Number函数去除尾随零:
const number = 15.5;
Number(number.toFixed(2)); // 15.5
const number = 1.7777777;
Number(number.toFixed(2)); // 1.78
在Node.js环境中,我只使用roundTo模块:
const roundTo = require('round-to');
...
roundTo(123.4567, 2);
// 123.46