如何在 JavaScript 中将数字四舍五入为多个重要的前导数字?



我想使用纯JavaScript将一个数字四舍五入到2个前导数字。 我想粗略地了解数字及其大小,但我不想用太多数字打扰听众。

所以 6832 应该四舍五入到 6800,但8773278475应该四舍五入到 8800000000,而不是8773278400。

这个函数为我提供了正确的整数结果:

/**
* @param {integer} num - The number to round
* @param {integer} leadingDigits - How many significant digits at the start to keep
* @returns {integer} rounded num
*/
function round(num, leadingDigits) {
let precision = Math.pow(10, num.toString().length - leadingDigits);
return Math.round(num / precision) * precision;
}
console.log(round(6832, 2));
console.log(round(8773278475, 2));
console.log(round(8, 2));

这将返回,如预期:

6800
8800000000
8

但由于.toString().length黑客攻击,它无法浮动。如果有人有更好的解决方案,请随时发布。

一个好的解决方案是简短而易于理解的。

最新更新