程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了根据给定的最少计数四舍五入一个数字?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决根据给定的最少计数四舍五入一个数字??

开发过程中遇到根据给定的最少计数四舍五入一个数字?的问题如何解决?下面主要结合日常开发的经验,给出你关于根据给定的最少计数四舍五入一个数字?的解决方法建议,希望对你解决根据给定的最少计数四舍五入一个数字?有所启发或帮助;

我正在编写一个函数,根据给定的最少计数对数字进行四舍五入。

例如,

1.2345 with a least count of 0.01 should becoume 1.23
1.23 with a least count of 0.5 should become 1
1.52 with a least count of 0.2 should become 1.4
etc...

这是我的解决方案,但感觉有点做作,有人可以就如何改进它提出任何建议吗?跟进,可以使用正则表达式吗,这会是一个更稳定的实现吗?

const round = (num,leastCount) => {
  const numdecimals = `${leastCount}`.split('.')?.[1]?.length || 0;

  const newnumber = Math.round(num * Math.pow(10,numdecimals) + number.EPSILON - num * Math.pow(10,numdecimals) % (leastCount * Math.pow(10,numdecimals))) / Math.pow(10,numdecimals)


  return newnumber

}

console.log(round(1.2345,0.01)) // Expected: 1.23
console.log(round(5.66,1)) // Expected: 5
console.log(round(2.375,0.005)) // Expected: 2.375
console.log(round(1.33,0.1)); // Expected: 1.3
console.log(round(2,0.001)); // Expected: 2
console.log(round(1.7512323,0.0001)); // Expected: 1.7512
console.log(round(1.52,0.2)); // Expected: 1.4
@H_489_19@ @H_489_19@

解决方法

一个简单的递增 while 循环可能是最简单的解决方案。

增加 n 的乘数 leastCount,直到结果乘积大于目标 num

const round = (num,leastCount) => {
  if (num == 0) return 0;
  let n = 0;
  while (n * leastCount <= Math.abs(num)) {
    n++;
  }
  return (n - 1) * leastCount * (num < 0 ? -1 : 1);
}

console.log(round(1.2345,0.01)) // Expected: 1.23
console.log(round(5.66,1)) // Expected: 5
console.log(round(2.375,0.005)) // Expected: 2.375
console.log(round(1.33,0.1)); // Expected: 1.3
console.log(round(2,0.001)); // Expected: 2
console.log(round(1.7512323,0.0001)); // Expected: 1.7512
console.log(round(1.52,0.2)); // Expected: 1.4
@H_489_19@ @H_489_19@

回复评论

奇怪的分数是由 JavaScript handles floating point values 方式引起的,可以用不同的方式处理,具体取决于您的实现和需求。

我在下面的示例中使用了 this solution,以及一种不同甚至更简单的数学方法:

const round = (num,leastCount) => {
  if (num == 0) return 0;
  let intermediate = Math.floor(num / leastCount) * leastCount; // Find value
  return parseFloat(intermediate.toPrecision(12)); // Round of excessive decimals
}

console.log(round(1.2345,0.2)); // Expected: 1.4
@H_489_19@ @H_489_19@

@H_489_19@

@H_489_19@

大佬总结

以上是大佬教程为你收集整理的根据给定的最少计数四舍五入一个数字?全部内容,希望文章能够帮你解决根据给定的最少计数四舍五入一个数字?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。