首页 > 解决方案 > 如何在javascript中舍入十进制数

问题描述

我有这个十进制数: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);
}

标签: javascriptroundingfloor

解决方案


如果你这样做是因为你需要打印/显示一个值,那么我们不需要留在数字领域:把它变成一个字符串,然后把它切碎:

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}`;

当然,如果您不是为了演示而这样做,那么可能应该首先回答“您为什么认为您需要这样做”(因为它使涉及该数字的后续数学无效)的问题,因为帮助您做错事是实际上并没有帮助,而是使事情变得更糟。


推荐阅读