如何将整数四舍五入到<最近的大数>在鲁比?最近的大数>
假设我有以下任何号码:
230957 或 83487或 第4785
章 300000 或 90000 或 分别是5000?
Say I have any of the following numbers:
230957 or
83487 or
4785
What is a way in Ruby I could return them as
300000 or
90000 or
5000, respectively?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
用你的例子:
With your examples:
并获得额外学分:
And for extra credit:
Math.round 接受负数。如果您只想查找最接近的 10 个,则可以执行
(my_num).round(-1)
。唯一的缺点是这里无法合并 ceil,因此它并不总是向上舍入 -
4.round(-1)
将返回 0。Math.round accepts negative numbers. If you are only looking for the nearest 10, you can do
(my_num).round(-1)
.The only drawback being that there's no way to incorporate ceil here, so it doesn't always round up --
4.round(-1)
will return 0.在 Rails 中,您可能还喜欢“number_to_ human”帮助器,它会自动选择一个合适的维度进行舍入。
http://api.rubyonrails.org/classes/ActionView /Helpers/NumberHelper.html#method-i-number_to_ human
In Rails, you may also like the "number_to_human" helper, which automatically chooses a good dimension to round to.
http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#method-i-number_to_human
我实际上没有在 Ruby 中完成任何编码,但是如果您首先将其推到您想要的数字,您就可以使用标准舍入函数来完成此操作。
示例:
舍入
2.30957 = 2
,或舍入到上限/舍入值+ 0.5
以使其达到较高值而不是较低值。希望这有帮助!
I haven't actually done any coding in Ruby, but you would be able to do that with a standard rounding function if you pushed it over to the digit you wanted first.
Example:
Round
2.30957 = 2
, or Round to Ceiling/Round value+ 0.5
to get it to go to the upper value rather than the lower.Hope this helps!
它看起来有点难看,但作为第一个镜头(每次都向上舍入)......
更好(四舍五入正确):
It looks a little ugly, but as a first shot (rounds up everytime) ...
Better (rounds correct):
这是我的版本:
这个方法非常污点,看起来很丑……但是……它处理了一些其他方法不能处理的边缘情况,例如:
以下是一些示例用法:
Here is my version:
This method is very bloted and looks so ugly... BUT... it handles a few edge cases that the others dont such as:
Here are some examples of usage:
一个简单的建议:
使用它:
A simple suggestion:
To use it: