我有这个十进制数:1.12346
我现在只想保留4位小数但我想向下舍入以便返回:1.1234。现在它返回:1.1235这是错误的。
有效。我想要最后两个数字:“46”向下舍入为“4”而不是达到“5”
这怎么可能呢?
var nums = 1.12346;
nums = MathRound(nums, 4);
console.log(nums);
function MathRound(num, nrdecimals) {
return num.toFixed(nrdecimals);
}
如果你这样做是因为你需要打印/显示一个值,那么我们就不需要留在数字中了:把它变成一个字符串,并把它砍掉:
let nums = 1.12346;
// take advantage of the fact that
// bit operations cause 32 bit integer conversion
let intPart = (nums|0);
// then get a number that is _always_ 0.something:
let fraction = nums - intPart ;
// and just cut that off at the known distance.
let chopped = `${fraction}`.substring(2,6);
// then put the integer part back in front.
let finalString = `${intpart}.${chopped}`;
当然,如果你不是为了演示而做这个问题,那么“为什么你认为你需要这样做”的问题(因为它使涉及这个数字的后续数学无效)应该首先回答,因为帮助你做错事是实际上没有帮助,但让事情变得更糟。
我认为这样做会有所帮助。基本上纠正了整理。
var nums = 1.12346;
nums = MathRound(nums, 4);
console.log(nums);
function MathRound(num, nrdecimals) {
let n = num.toFixed(nrdecimals);
return (n > num) ? n-(1/(Math.pow(10,nrdecimals))) : n;
}
这是与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));
var nums = 1.12346;
var dec = 10E3;
var intnums = Math.floor(nums * dec);
var trim = intnums / dec;
console.log(trim);