Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A way to round Floats down

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.

like image 814
Michael Koper Avatar asked Aug 17 '11 09:08

Michael Koper


People also ask

How do you round off floats?

Round() Round() is a built-in function available with python. It will return you a float number that will be rounded to the decimal places which are given as input. If the decimal places to be rounded are not specified, it is considered as 0, and it will round to the nearest integer.

How do I round down in Python?

The round() function rounds a number to the nearest whole number. The math. ceil() method rounds a number up to the nearest whole number while the math. floor() method rounds a number down to the nearest whole number.

How do you round down?

If the number you are rounding is followed by 5, 6, 7, 8, or 9, round the number up. Example: 38 rounded to the nearest ten is 40. If the number you are rounding is followed by 0, 1, 2, 3, or 4, round the number down. Example: 33 rounded to the nearest ten is 30.


2 Answers

1.9999.to_i
#=> 1
1.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
  end
end
like image 183
fl00r Avatar answered Sep 20 '22 12:09

fl00r


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
like image 27
geronime Avatar answered Sep 20 '22 12:09

geronime