Round floats to the nearest X

July 18, 2007 code 2 min read

For those pesky times when whole numbers just won’t cut it, but you only want some precision.

7.7.round(0.5)   #=> 7.5
7.95.round(0.5)  #=> 8
8.2.round(1.5)   #=> 7.5
8.3.round(1.5)   #=> 9

The magic, courtesy of Daniel Morrison:

class Float
  def round(round_to = 1.0)
    mod = self % round_to
    rounded = self - mod + (mod >= round_to/2.0 ? round_to : 0)
    rounded % 1 == 0 ? rounded.to_i : rounded

Note that do to some quirks with Ruby’s handling of floats, you won’t get what you expect in some situations:

3.5.round(0.2)   #=> 3.4, instead of 3.6
This content is open source. Suggest Improvements.


avatar of Brandon Keepers I am Brandon Keepers, and I work at GitHub on making Open Source more approachable, effective, and ubiquitous. I tend to think like an engineer, work like an artist, dream like an astronaut, love like a human, and sleep like a baby.