我越来越号码,如圆形红宝石浮动向上或向下调整至最接近0.05
2.36363636363636
4.567563
1.234566465448465
10.5857447736
我将如何获取Ruby圆这些数字向上(或向下)到最近的0.05?
我越来越号码,如圆形红宝石浮动向上或向下调整至最接近0.05
2.36363636363636
4.567563
1.234566465448465
10.5857447736
我将如何获取Ruby圆这些数字向上(或向下)到最近的0.05?
检查此链接,我认为这是你需要的。 Ruby rounding
class Float
def round_to(x)
(self * 10**x).round.to_f/10**x
end
def ceil_to(x)
(self * 10**x).ceil.to_f/10**x
end
def floor_to(x)
(self * 10**x).floor.to_f/10**x
end
end
感谢您的链接!这些方法完美地工作。 – dotty 2009-08-28 10:54:45
尼斯链接。尽管如此,答案会更好,因此它可以独立存在,尤其是因为链接的代码不完全符合OP要求的内容,即四舍五入到最接近的0.05,但会舍入到特定的小数位。 – tvanfosson 2009-08-28 11:00:51
更糟糕的是,这篇文章实际上是重新实现了内置的ruby函数(小数位数),这是一个坏主意。 – Rob 2012-04-05 14:32:46
[2.36363636363636, 4.567563, 1.23456646544846, 10.5857447736].map do |x|
(x*20).round/20.0
end
#=> [2.35, 4.55, 1.25, 10.6]
一般而言,算法“舍入到最接近的X”是:
round(x/precision)) * precision
有时最好通过1/precision
相乘,因为它是一个整数(且因此它工作得更快一些):
round(x * (1/precision))/(1/precision)
在你的情况,这将是:
round(x * (1/0.05))/(1/0.05)
这将计算为:
round(x * 20)/20;
我不知道任何的Python,不过,这样的语法可能不正确的,但我敢肯定,你可以弄明白。
为了使小数除以20.0 - > round(x * 20)/ 20.0; – Irukandji 2009-11-30 10:43:31
对于ruby:'(7.125 * 20).round/20.0 => 7.15' – 2012-03-23 19:14:39
这里的舍入任何给定步长值一般功能:
发生在lib目录下:
lib/rounding.rb
class Numeric
# round a given number to the nearest step
def round_by(increment)
(self/increment).round * increment
end
end
和规范:
require 'rounding'
describe 'nearest increment by 0.5' do
{0=>0.0,0.5=>0.5,0.60=>0.5,0.75=>1.0, 1.0=>1.0, 1.25=>1.5, 1.5=>1.5}.each_pair do |val, rounded_val|
it "#{val}.round_by(0.5) ==#{rounded_val}" do val.round_by(0.5).should == rounded_val end
end
end
与用法:
require 'rounding'
2.36363636363636.round_by(0.05)
hth。
不太精确,但这种方法是大多数人都在谷歌上搜索这个页面
(5.65235534).round(2)
#=> 5.65
5.6355.round(2)!= 5.65,但TS想要5.65 – 2013-04-11 05:14:50
此解决方案只将数字四舍五入到小数点后两位,它不返回根据要求舍入到最接近的0.05。 – 2013-05-02 02:01:49
在某些方面你是对的,我应该删除这个答案。但在另一层面上,这是一个非常受欢迎的问题,在人们发现这个答案很有帮助的搜索中被链接到,所以我要保持它可见 – 2014-07-05 14:45:22
有可能与String
类的%
法圆号码。
例如
"%.2f" % 5.555555555
会给"5.56"
作为结果(字符串)。
要获得舍入结果无小数,使用Float's .round
5.44.round
=> 5
5.54.round
=> 6
红宝石2现在有一个圆形的功能:
# Ruby 2.3
(2.5).round
3
# Ruby 2.4
(2.5).round
2
也有红宝石2.4
选项,如::even
,:up
和:down
e。G;
(4.5).round(half: :up)
5
你意识到那些不是整数,对吗? – 2009-08-28 13:58:35