Module: Sinatra::Numeric::Helpers

Defined in:
lib/sinatra/support/numeric.rb

Instance Method Summary collapse

Instance Method Details

#currency(number, opts = {}) ⇒ String?

Formats a number into a currency display. Uses the following settings:

  • settings.default_currency_unit (defaults to ‘$’)

  • settings.default_currency_precision (defaults to 2)

  • settings.default_currenty_separator (defaults to ‘,’)

Examples:


currency(100) == "$ 100.00"
# => true

currency(100, :unit => "£") == "£ 100.00"
# => true

currency(100, :precision => 0) == "$ 100"
=> # true

# somewhere in your sinatra context after registering Sinatra::Support
set :default_currency_unit, '£'
set :default_currency_precision, 3
set :default_currency_separator, ' '

currency(100) == "£ 100.000"
# => true

Parameters:

  • number (Numeric)

    the number you wish to display as a currency.

  • opts (Hash) (defaults to: {})

    the various options available.

Options Hash (opts):

  • :unit (#to_s) — default: defaults to '$'
  • :precision (Fixnum) — default: defaults to 2
  • :separator (#to_s) — default: defaults to ','

Returns:

  • (String)

    the formatted string based on ‘number`.

  • (nil)

    if given nil or an empty string.



75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/sinatra/support/numeric.rb', line 75

def currency(number, opts = {})
  return if number.to_s.empty?

  unit      = opts[:unit]      || settings.default_currency_unit
  precision = opts[:precision] || settings.default_currency_precision
  separator = opts[:separator] || settings.default_currency_separator

  ret = "%s %.#{ Integer(precision) }f" % [unit, number]
  parts = ret.split('.')
  parts[0].gsub!(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{separator}")
  parts.join('.')
end

#percentage(number, precision = 2) ⇒ String?

Show the percentage representation of a numeric value.

Examples:

percentage(100) == "100.00%"
percentage(100, 0) == "100%"

Parameters:

  • number (Numeric)

    A numeric value

  • precision (Fixnum) (defaults to: 2)

    (defaults to 2) Number of decimals to show.

Returns:

  • (String)

    the number displayed as a percentage

  • (nil)

    given a nil value or an empty string.



98
99
100
101
102
103
# File 'lib/sinatra/support/numeric.rb', line 98

def percentage(number, precision = 2)
  return if number.to_s.empty?

  ret = "%02.#{ precision }f%" % number
  ret.gsub(/\.0*%$/, '%')
end