Skip to content

Instantly share code, notes, and snippets.

@djgraham
Created February 29, 2012 07:36
Show Gist options
  • Save djgraham/1938898 to your computer and use it in GitHub Desktop.
Save djgraham/1938898 to your computer and use it in GitHub Desktop.
Swedish Rounding module - Extends Numeric to allow you to do "swedish rounding" - see http://en.wikipedia.org/wiki/Swedish_rounding
# this module adds rounding to the nearest decimal number.
# by default it rounds to the nearest 10 pence
# but you can also round to the nearest 50 / 1000 or whatever..
#
module ExtendNumericRounding
def roundup( nearest=10 )
self % nearest == 0 ? self : self + nearest - ( self % nearest )
end
def rounddown( nearest=10 )
self % nearest == 0 ? self : self - ( self % nearest )
end
def roundnearest( nearest=10 )
up = roundup( nearest )
down = rounddown( nearest )
if ( up - self ) <= ( self - down )
return up
else
return down
end
end
end
Numeric.send(:include, ExtendNumericRounding)
@djgraham
Copy link
Author

(Note default is to round to nearest 10, but you can specify to round to the nearest 100, 1000... etc. You can also use it to round to to any nearest number too..

Example using irb console:-

ree-1.8.7-2010.02 :001 > require "lib/extend_numeric_rounding"
=> true
ree-1.8.7-2010.02 :002 > 10.roundnearest
=> 10
ree-1.8.7-2010.02 :003 > 13.roundnearest
=> 10
ree-1.8.7-2010.02 :004 > 49.roundnearest
=> 50
ree-1.8.7-2010.02 :005 > 49.roundnearest(100)
=> 0
ree-1.8.7-2010.02 :006 > 50.roundnearest(100)
=> 100
ree-1.8.7-2010.02 :007 > 543.roundnearest(100)
=> 500
ree-1.8.7-2010.02 :013 > 543.roundnearest(5)
=> 545
ree-1.8.7-2010.02 :014 > 543.roundnearest(4)
=> 544
ree-1.8.7-2010.02 :015 > 543.roundnearest(3)
=> 543
ree-1.8.7-2010.02 :016 > 543.roundnearest(300)
=> 600
ree-1.8.7-2010.02 :017 > 543.roundnearest(320)
=> 640

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment