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

Float to HTML fraction entity (See related posts)

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

class Float
    def html_fraction
        self.to_s.
            sub(/(.+)\.0$/,     '\1'        ).  # Zero decimal
            sub(/(-?\d+)\.25$/, '\1¼').  # One quarter
            sub(/(-?\d+)\.5$/,  '\1½').  # One half
            sub(/(-?\d+)\.75$/, '\1¾').  # Three quarters
            sub(/^(-?)0(&.+)/,  '\1\2'      )   # Strip leading zeroes
    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 on this post

Murt posts on Aug 03, 2006 at 21:41
Using the modulo operator (%) you can do it like this:
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...
sporkyy posts on Aug 08, 2006 at 14:16
Yeah, I'm definately no mathematician. That's one of the reasons I switched from a mathematical approach to a regular expressions based method. It also was only 1 line. I just love solving things in only 1 line.

This is for a personal project, a comic book database. I've been reimplementing it for years in Access, ASP, JSP, PHP, ColdFusion and now Ruby On Rails. (I think of it as my own little personal Pet Store application.) I have issues numbered with negative numbers and issues with fractions, but no issues with negative fractions. Since you brought it up now, I figure it's just a matter of time, though.

Thanks for the addition.

You need to create an account or log in to post comments to this site.


Click here to browse all 4858 code snippets

Related Posts