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 

Number to Currency with Cents

A slight alteration to the default Rails currency formatting helper to show numbers in cents if the number is less than $1.00. For example $0.99 would instead become 99¢.

def number_to_currency_with_cents(number, options = {})
    options = options.stringify_keys
    precision = options.delete('precision') { 2 }
    unit = options.delete('unit') { '$' }
    fractional_unit = options.delete('fractional_unit') { '¢' }
    separator = options.delete('separator') { '.' }
    delimiter = options.delete('delimiter') { ',' }
    separator = '' unless precision > 0
    begin
        fraction = number.abs % 1.0
        body = number.floor
        if body != 0 || body == 0 && fraction == 0 then
            parts = number_with_precision(number, precision).split('.')
            unit + number_with_delimiter(parts[0], delimiter) + separator + parts[1].to_s
        else
            (fraction * 100).to_i.to_s + fractional_unit
        end
    rescue
        number
    end
end


I'm really tempted to go through and replace that whole thing with my own code, but it works, so I'm happy.
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS