如何舍入到下一个最大数字? [英] How to round to the next largest number?

查看:53
本文介绍了如何舍入到下一个最大数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的数字总是四舍五入到闭合的上限数字,如下所示:

I want my number to always get rounded to the closes upper number like this:

1.2 => 2

1.4 => 2

2.5 => 3

2.9 => 3

我该如何使用JavaScript?

How can i do this with JavaScript?

推荐答案

您可以使用Math.ceil()函数.

You can use the Math.ceil() function.

Math.ceil(1.1) // returns 2

相反,如果您想舍入 ,则可以使用Math.floor()

Conversely, if you wanted to round down you'd use Math.floor()

Math.floor(1.8) // returns 1

这是一个演示:

console.table([1, 1.25, 1.49, 1.5, 1.75, 2].map(n => ({
  n,
  "Math.floor(n)": Math.floor(n),
  "Math.ceil(n)": Math.ceil(n),
  "Math.round(n)": Math.round(n),
})));

<script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script><script>console.config({maximize:true,timeStamps:false})</script><style>.as-console-wrapper{display:block;}</style>

注意:地板和天花板功能并非javascript独有.有关更多信息,请参见维基百科条目.

这篇关于如何舍入到下一个最大数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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