我有这个十进制数:1.12346
我现在只想保留 4 位小数,但我想向下舍入以便返回:1.1234。现在它返回:1.1235,这是错误的。
有效。我想要最后 2 个数字:“46”向下舍入为“4”而不是向上舍入为“5”
这怎么可能?
var nums = 1.12346;
nums = MathRound(nums, 4);
console.log(nums);
function MathRound(num, nrdecimals) {
return num.toFixed(nrdecimals);
}
最佳答案
这与 How to round down number 2 decimal places? 是同一个问题.您只需对额外的小数位进行调整。
Math.floor(1.12346 * 10000) / 10000
console.log(Math.floor(1.12346 * 10000) / 10000);
如果你想把它作为一个可重用的函数,你可以这样做:
function MathRound (number, digits) {
var adjust = Math.pow(10, digits); // or 10 ** digits if you don't need to target IE
return Math.floor(number * adjust) / adjust;
}
console.log(MathRound(1.12346, 4));
关于javascript - 如何在javascript中舍入小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55388282/