Class: Latinum::Formatters::DecimalCurrencyFormatter
- Inherits:
-
Object
- Object
- Latinum::Formatters::DecimalCurrencyFormatter
- Defined in:
- lib/latinum/formatters.rb
Overview
Formats a currency using a standard decimal notation.
Instance Method Summary collapse
-
#format(amount, **options) ⇒ Object
Formats the amount using the configured symbol, separator, delimeter, and places.
-
#from_integral(amount) ⇒ Object
Converts the amount to a decimal, taking into account the number of specified decimal places.
-
#initialize(**options) ⇒ DecimalCurrencyFormatter
constructor
A new instance of DecimalCurrencyFormatter.
- #round(amount) ⇒ Object
-
#to_integral(amount) ⇒ Object
Converts the amount directly to an integer, truncating any decimal part, taking into account the number of specified decimal places.
Constructor Details
#initialize(**options) ⇒ DecimalCurrencyFormatter
Returns a new instance of DecimalCurrencyFormatter.
55 56 57 58 59 60 61 62 63 |
# File 'lib/latinum/formatters.rb', line 55 def initialize(**) @symbol = [:symbol] || '$' @separator = [:separator] || '.' @delimeter = [:delimter] || ',' @places = [:precision] || 2 @zero = [:zero] || '0' @name = [:name] end |
Instance Method Details
#format(amount, **options) ⇒ Object
Formats the amount using the configured symbol, separator, delimeter, and places. e.g. “$5,000.00 NZD”. Rounds the amount to the specified number of decimal places.
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
# File 'lib/latinum/formatters.rb', line 72 def format(amount, **) # Round to the desired number of places. Truncation used to be the default. amount = amount.round(@places) integral, fraction = amount.abs.to_s('F').split(/\./, 2) # The sign of the number sign = '-' if amount < 0 # Decimal places, e.g. the '.00' in '$10.00' fraction = fraction[0...@places].ljust(@places, @zero) # Grouping, e.g. the ',' in '$10,000.00' remainder = integral.size % 3 groups = integral[remainder..-1].scan(/.{3}/).to_a groups.unshift(integral[0...remainder]) if remainder > 0 symbol = .fetch(:symbol, @symbol) value = "#{sign}#{symbol}#{groups.join(@delimeter)}" name = .fetch(:name, @name) suffix = name ? " #{name}" : '' if @places > 0 "#{value}#{@separator}#{fraction}#{suffix}" else "#{value}#{suffix}" end end |
#from_integral(amount) ⇒ Object
Converts the amount to a decimal, taking into account the number of specified decimal places.
112 113 114 |
# File 'lib/latinum/formatters.rb', line 112 def from_integral(amount) (amount.to_d / 10**@places) end |
#round(amount) ⇒ Object
65 66 67 |
# File 'lib/latinum/formatters.rb', line 65 def round(amount) return amount.round(@places) end |
#to_integral(amount) ⇒ Object
Converts the amount directly to an integer, truncating any decimal part, taking into account the number of specified decimal places.
105 106 107 |
# File 'lib/latinum/formatters.rb', line 105 def to_integral(amount) (amount * 10**@places).to_i end |