Search code examples
rubydecimalfloor

Floor function to float numbers


I wrote a ruby code that rounds down a number as follows:

def round_down(number)
  number.to_s.split(/\./)[0].to_i
end
round_down(1.9)

Does somebody know a more rubystic way to achieve this?


Solution

  • JavaScript's Math.floor function already exists in Ruby: 1.9.floor

    What you are doing in your code is actually something else, which also exists: 1.9.truncate

    They are the same for positive numbers, but for negative numbers truncate behaves like ceil:

    • floor rounds down
    • ceil rounds up
    • truncate rounds towards zero