将红宝石浮点数向上或向下舍入到最接近的 0.05
我收到诸如“
2.36363636363636
4.567563
1.234566465448465
10.5857447736
如何让 Ruby 将这些数字向上(或向下)四舍五入到最接近的 0.05?”之类的数字?
I'm getting numbers like
2.36363636363636
4.567563
1.234566465448465
10.5857447736
How would I get Ruby to round these numbers up (or down) to the nearest 0.05?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
查看此链接,我认为这就是您所需要的。
Ruby 舍入
Check this link out, I think it's what you need.
Ruby rounding
一般来说,“舍入到最接近的x”的算法是:
有时乘以
1 / precision
会更好,因为它是一个整数(因此它的工作速度更快一些) ):在你的情况下,这将是:
它将评估为:
不过,我不知道任何Python,所以语法可能不正确,但我相信你可以弄清楚。
In general the algorithm for “rounding to the nearest x” is:
Sometimes is better to multiply by
1 / precision
because it is an integer (and thus it works a bit faster):In your case that would be:
which would evaluate to:
I don’t know any Python, though, so the syntax might not be correct but I’m sure you can figure it out.
要四舍五入到最接近的 2 位:
To round to the nearest 2 places instead:
这是一个按任何给定步长值舍入的通用函数:
放置在 lib:
以及 spec:
和用法:
hth 中。
Here's a general function that rounds by any given step value:
place in lib:
and the spec:
and usage:
hth.
Ruby 2 现在有一个 round 函数:
ruby
2.4
中还有一些选项,例如::even
、:up
和:down< /代码>
例如;
Ruby 2 now has a round function:
There are also options in ruby
2.4
like::even
,:up
and:down
e.g;
可以使用
String
类的%
方法对数字进行四舍五入。例如,
将给出
"5.56"
作为结果(字符串)。It’s possible to round numbers with
String
class’s%
method.For example
would give
"5.56"
as result (a string).要获得不带小数的舍入结果,请使用 Float 的 .圆形
To get a rounding result without decimals, use Float's .round
我知道这个问题很老了,但我喜欢与世界分享我的发明以帮助其他人:这是一种用步长舍入浮点数,将小数舍入到最接近给定数字的方法;它对于四舍五入产品价格很有用,例如:
I know that the question is old, but I like to share my invention with the world to help others: this is a method for rounding float number with step, rounding decimal to closest given number; it's usefull for rounding product price for example: