lib/latinum/formatters.rb in latinum-1.7.0 vs lib/latinum/formatters.rb in latinum-1.7.1

- old
+ new

@@ -26,10 +26,16 @@ class PlainFormatter def initialize(name:) @name = name end + # Parse a string into an amount. + # @returns [BigDecimal] The parsed amount. + def parse(string) + BigDecimal(string) + end + # Formats the amount using a general notation. # e.g. "5.0 NZD". # @returns [String] The formatted string. def format(amount) "#{amount.to_s('F')} #{@name}" @@ -53,22 +59,30 @@ # Formats a currency using a standard decimal notation. class DecimalCurrencyFormatter def initialize(**options) @symbol = options[:symbol] || '$' @separator = options[:separator] || '.' - @delimeter = options[:delimeter] || ',' + @delimiter = options[:delimiter] || ',' @places = options[:precision] || 2 @zero = options[:zero] || '0' @name = options[:name] end def round(amount) return amount.round(@places) end - # Formats the amount using the configured symbol, separator, delimeter, and places. + # Parse a string into an amount using the configured separator and delimiter. + # @returns [BigDecimal] The parsed amount. + def parse(string) + BigDecimal( + string.gsub(/[^\-0-9#{@separator}]/, '').gsub(@separator, '.') + ) + end + + # Formats the amount using the configured symbol, separator, delimiter, and places. # e.g. "$5,000.00 NZD". Rounds the amount to the specified number of decimal places. # @returns [String] The formatted string. def format(amount, places: @places, **options) # Round to the desired number of places. Truncation used to be the default. amount = amount.round(places).to_d @@ -85,10 +99,10 @@ remainder = integral.size % 3 groups = integral[remainder..-1].scan(/.{3}/).to_a groups.unshift(integral[0...remainder]) if remainder > 0 symbol = options.fetch(:symbol, @symbol) - value = "#{sign}#{symbol}#{groups.join(@delimeter)}" + value = "#{sign}#{symbol}#{groups.join(@delimiter)}" name = options.fetch(:name, @name) suffix = name ? " #{name}" : '' if places > 0