Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

James Robertson http://www.r0bertson.co.uk

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Floating point round off

Source: Ruby: Floating point round off [hans-eric.com]

With a little monkey patching we can add custom round off methods to the Float class.

   1  
   2  class Float
   3    def round_to(x)
   4      (self * 10**x).round.to_f / 10**x
   5    end
   6  
   7    def ceil_to(x)
   8      (self * 10**x).ceil.to_f / 10**x
   9    end
  10  
  11    def floor_to(x)
  12      (self * 10**x).floor.to_f / 10**x
  13    end
  14  end

Example usage:

num = 138.249
num.round_to(2)
# => 138.25

num.floor_to(2)
# => 138.24

num.round_to(-1)
# => 140.0



« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS