A way to round Floats down A way to round Floats down ruby ruby

A way to round Floats down


1.9999.to_i#=> 11.9999.floor#=> 1

answered 1 sec ago fl00r

"%.2f" % 1.93213#=> 1.93

@kimmmo is right.

class Float  def round_down(n=0)    self.to_s[/\d+\.\d{#{n}}/].to_f  endend


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  endend1.9991.round_down(3) => 1.9991.9991.round_down(2) => 1.991.9991.round_down(0) => 1.01.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)  endend


Looks like you just want to strip decimals after n

class Float  def round_down(n=0)    int,dec=self.to_s.split('.')    "#{int}.#{dec[0...n]}".to_f  endend1.9991.round_down(3) => 1.9991.9991.round_down(2) => 1.991.9991.round_down(0) => 1.01.9991.round_down(10) => 1.9991

(Edit: slightly more efficient version without the regexp)