如何在 ruby 中限制和舍入数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/884512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to cap and round number in ruby
提问by Arthur
I would like to "cap" a number in Ruby (on Rails).
我想在 Ruby (on Rails) 中“限制”一个数字。
For instance, I have, as a result of a function, a float but I need an int.
例如,作为函数的结果,我有一个浮点数,但我需要一个整数。
I have very specific instructions, here are some examples:
我有非常具体的说明,以下是一些示例:
If I get 1.5I want 2but if I get 2.0I want 2(and not 3)
如果我得到1.5我想要2但如果我得到2.0我想要2(而不是3)
Doing number.round(0) + 1won't work.
做是number.round(0) + 1行不通的。
I could write a function to do this but I am sure one already exists.
我可以编写一个函数来做到这一点,但我确信一个函数已经存在。
If, nevertheless, it does not exist, where should I create my cap function?
尽管如此,如果它不存在,我应该在哪里创建我的 cap 函数?
回答by Patrick McDonald
How about number.ceil?
怎么样number.ceil?
This returns the smallest Integer greater than or equal to number.
这将返回大于或等于 number 的最小整数。
Be careful if you are using this with negative numbers, make sure it does what you expect:
如果您将它与负数一起使用,请小心,确保它符合您的预期:
1.5.ceil #=> 2
2.0.ceil #=> 2
(-1.5).ceil #=> -1
(-2.0).ceil #=> -2
回答by meso_2600
.ceil is good, but remember, even smallest value in float will cause this:
.ceil 很好,但请记住,即使是 float 中的最小值也会导致这种情况:
a = 17.00000000000002
17.0
a.ceil
18
回答by Pesto
Use Numeric#ceil:
使用数字#ceil:
irb(main):001:0> 1.5.ceil
=> 2
irb(main):002:0> 2.0.ceil
=> 2
irb(main):003:0> 1.ceil
=> 1
回答by Sparr
float.ceilis what you want for positive numbers. Be sure to consider the behavior for negative numbers. That is, do you want -1.5 to "cap" to -1 or -2?
float.ceil是您想要的正数。请务必考虑负数的行为。也就是说,您希望 -1.5 将“上限”为 -1 还是 -2?

