DZone 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

# Float To HTML Fraction Entity

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

class Float def to_html_fraction fraction = case self.abs % 1.0 when 1.0 / 2 then '½' # One half when 1.0 / 4 then '¼' # One quarter when 3.0 / 4 then '¾' # Three quarters when 1.0 / 3 then '⅓' # One third when 2.0 / 3 then '⅔' # Two thirds when 1.0 / 5 then '⅕' # One fifth when 2.0 / 5 then '⅖' # Two fifths when 3.0 / 5 then '⅗' # Three fifths when 4.0 / 5 then '⅘' # Four fifths when 1.0 / 6 then '⅙' # One sixth when 5.0 / 6 then '⅚' # Five sixths when 1.0 / 8 then '⅛' # One eighth when 3.0 / 8 then '⅜' # Three eighths when 5.0 / 8 then '⅝' # Five eighths when 7.0 / 8 then '⅞' # Seven eighths end if fraction body = case self.floor when -1 then '-' when 0 then '' else self.to_i.to_s end body + fraction else self.to_s end end end

And it works something like this:

>> (0.1).html_fraction => 0.1 >> (0.25).html_fraction => ¼ >> (0.50).html_fraction => ½ >> (0.75).html_fraction => ¾ >> (1.0).html_fraction => 1.0 >> (2.25).html_fraction => 2¼ >> (3.5).html_fraction => 3½ >> (4.75).html_fraction => 4¾ >> (5.85).html_fraction => 5.85 >> (-1.5).html_fraction => -1½ >> (-1.6).html_fraction => -1.6; >> (-0.25).html_fraction => -¼

## Comments

## Snippets Manager replied on Mon, 2012/05/07 - 2:25pm

## Snippets Manager replied on Thu, 2006/08/03 - 8:35pm

`class Float def html_fraction fraction = case self.abs%1.0 when 0.25 : '¼' when 0.5 : '½' when 0.75 : '¾' end if fraction body = case self.floor when -1 : '-' when 0 : '' else self.to_i.to_s end body + fraction else self.to_s end end end`

Then it works also for 2.50 and negative numbers. But it might be less readable for non mathematicians...