一个圆的方式浮动下来 [英] A way to round Floats down
问题描述
我有解决方案,但我不喜欢它...也许有一个更好的办法。
这是我想要的:
1.9999.round_down(2)
#= > 1.99
1.9901.round_down(2)
#=> 1
我想出了这个解决方案,但是我想知道是否有更好的解决方案不喜欢,我把浮动两次)。有没有一种方法呢?因为我发现奇怪的是我找不到它。
$ p $ class Float
def round_down(n = 0)
((self * 10 ** n).to_i).to_f / 10 ** n
end
end
谢谢。
基于@kimmmo的回答,应该多一点高效:
class Flo
def round_down n = 0
s = self.to_s
l = s.index('。')+ 1 + n
s.length< = l? self:s [0,l] .to_f
end
end
1.9991.round_down(3)
=> 1.999
1.9991.round_down(2)
=> 1.99
1.9991.round_down(0)
=> 1.0
1.9991.round_down(5)
=> 1.9991
或基于@steenslag的回答,可能效率更高,因为没有字符串转换:
class Float
def round_down n = 0
n< 1? self.to_i.to_f:(self - 0.5 / 10 ** n).round(n)
end
end
Float round rounds it up or down. I always need it to round down.
I have the solution but i dont really like it... Maybe there is a better way.
This is what i want:
1.9999.round_down(2)
#=> 1.99
1.9901.round_down(2)
#=> 1
I came up with this solution but i would like to know if there is a better solution(I dont like that i convert the float twice). Is there already a method for this? Because I found it pretty strange that I couldnt find it.
class Float
def round_down(n=0)
((self * 10**n).to_i).to_f/10**n
end
end
Thanks.
Based on answer from @kimmmo this should be a little more efficient:
class Float
def round_down n=0
s = self.to_s
l = s.index('.') + 1 + n
s.length <= l ? self : s[0,l].to_f
end
end
1.9991.round_down(3)
=> 1.999
1.9991.round_down(2)
=> 1.99
1.9991.round_down(0)
=> 1.0
1.9991.round_down(5)
=> 1.9991
or based on answer from @steenslag, probably yet more efficient as there is no string conversion:
class Float
def round_down n=0
n < 1 ? self.to_i.to_f : (self - 0.5 / 10**n).round(n)
end
end
这篇关于一个圆的方式浮动下来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!