我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
当前回答
下面是一个原型方法:
Number.prototype.round = function(places){
places = Math.pow(10, places);
return Math.round(this * places)/places;
}
var yournum = 10.55555;
yournum = yournum.round(2);
其他回答
对我来说,Math.rround()没有给出正确的答案。我发现Fixed(2)效果更好。以下是两者的示例:
console.log(数学舍入(43000/80000)*100);//错误的答案console.log(((43000/80000)*100).toFixed(2));//正确回答
从现有的答案中,我找到了另一个似乎很有效的解决方案,它也可以发送字符串,并消除尾随零。
function roundToDecimal(string, decimals) {
return parseFloat(parseFloat(string).toFixed(decimals));
}
如果你派一些公牛来,那就不算什么了。。就像“阿帕”一样。或者它可能会抛出一个错误,我认为这是正确的方法。无论如何,隐藏应该修复的错误(通过调用函数)是不好的。
避免舍入到任意位数的二进制问题的适当方法是:
function roundToDigits(number, digits) {
return Number(Math.round(Number(number + 'e' + digits)) + 'e-' + digits);
}
修复toFixed()函数的一种方法是:
Number.prototype.toFixed = (prototype => {
const toFixed = prototype.toFixed;
// noinspection JSVoidFunctionReturnValueUsed
return function (fractionDigits) {
if (!fractionDigits) {
return toFixed.call(this);
} else {
// Avoid binary rounding issues
fractionDigits = Math.floor(fractionDigits);
const n = Number(Math.round(Number(+this + 'e' + fractionDigits)) + 'e-' + fractionDigits);
return toFixed.call(n, fractionDigits);
}
};
})(Number.prototype);
另一种方法是使用库。使用Lodash:
const _ = require("lodash")
const roundedNumber = _.round(originalNumber, 2)
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