将浮点数舍入到最接近的 <n> 倍数? [英] Round a float to the nearest multiple of <n>?

查看:31
本文介绍了将浮点数舍入到最接近的 <n> 倍数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将浮点值四舍五入到最接近的n"倍数?

How do I round a float value to the nearest multiple of "n"?

例如,将 21.673 舍入到最接近的 8 的倍数应为 24.

For instance, rounding 21.673 to the nearest multiple of 8 should result in 24.

而且,将 21.673 舍入到最接近的 4 的倍数应为 20.

And, rounding 21.673 to the nearest multiple of 4 should result in 20.

我需要 JavaScript 的解决方案.

I need the solution in JavaScript.

谢谢!

推荐答案

很简单

Math.round(value / n) * n

这篇关于将浮点数舍入到最接近的 <n> 倍数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆