繁体   English   中英

如何将数字四舍五入为 JavaScript 中的多个有效前导数字?

[英]How do I round a number to a number of significant leading digits in JavaScript?

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

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

这个 function 给了我正确的整数结果:

/**
 * @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 hack,它对于 float 失败。 如果有人有更好的解决方案,请随时发布。

一个好的解决方案简短易懂。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM