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

Todd Sayre http://del.icio.us/sporkyy

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

Float to HTML fraction entity

Uses HTML entities to display pretty fractional values for applicable floating point numbers.

   1  
   2  class Float
   3      def html_fraction
   4          self.to_s.
   5              sub(/(.+)\.0$/,     '\1'        ).  # Zero decimal
   6              sub(/(-?\d+)\.25$/, '\1¼').  # One quarter
   7              sub(/(-?\d+)\.5$/,  '\1½').  # One half
   8              sub(/(-?\d+)\.75$/, '\1¾').  # Three quarters
   9              sub(/^(-?)0(&.+)/,  '\1\2'      )   # Strip leading zeroes
  10      end
  11  end


And it works something like this:

   1  
   2  >> (0.1).html_fraction
   3  => 0.1
   4  >> (0.25).html_fraction
   5  => ¼
   6  >> (0.50).html_fraction
   7  => ½
   8  >> (0.75).html_fraction
   9  => ¾
  10  >> (1.0).html_fraction
  11  => 1.0
  12  >> (2.25).html_fraction
  13  => 2¼
  14  >> (3.5).html_fraction
  15  => 3½
  16  >> (4.75).html_fraction
  17  => 4¾
  18  >> (5.85).html_fraction
  19  => 5.85
  20  >> (-1.5).html_fraction
  21  => -1½
  22  >> (-1.6).html_fraction
  23  => -1.6;
  24  >> (-0.25).html_fraction
  25  => -¼
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS