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

Number to Currency with Cents (See related posts)

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¢.

   1  
   2  def number_to_currency_with_cents(number, options = {})
   3      options = options.stringify_keys
   4      precision = options.delete('precision') { 2 }
   5      unit = options.delete('unit') { '$' }
   6      fractional_unit = options.delete('fractional_unit') { '¢' }
   7      separator = options.delete('separator') { '.' }
   8      delimiter = options.delete('delimiter') { ',' }
   9      separator = '' unless precision > 0
  10      begin
  11          fraction = number.abs % 1.0
  12          body = number.floor
  13          if body != 0 || body == 0 && fraction == 0 then
  14              parts = number_with_precision(number, precision).split('.')
  15              unit + number_with_delimiter(parts[0], delimiter) + separator + parts[1].to_s
  16          else
  17              (fraction * 100).to_i.to_s + fractional_unit
  18          end
  19      rescue
  20          number
  21      end
  22  end


I'm really tempted to go through and replace that whole thing with my own code, but it works, so I'm happy.

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


Click here to browse all 5545 code snippets

Related Posts