Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 45 / 68

Rounding Numbers (floor, ceil, round)

In this lesson you will learn the difference between floor, ceil, and round so you can pick the right one for the job. This is for anyone searching for "Ruby round down round up round half".

.floor rounds down, .ceil rounds up, and .round rounds to nearest. "Shave it down", "push it up", and "go to whichever is closer" are useful mental labels.

The sample code shows 3.7.floor giving 3, 3.2.ceil giving 4, and 3.5.round giving 4. Calling a method directly on a number is a distinctly Ruby, object-oriented touch.

A common stumbling block for beginners is the very idea of calling a method on a numeric literal. The number 3.7 is itself an object you can call .floor on, which is a neat demonstration of Ruby's "everything is an object" philosophy.

round takes a second argument for the number of decimal places, giving you fine control. The choice changes your results, so match it to the purpose.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)