Skip to content

Instantly share code, notes, and snippets.

@tit
Created November 2, 2018 11:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tit/6ef0012603868ffc016b6267ec7d1f54 to your computer and use it in GitHub Desktop.
Save tit/6ef0012603868ffc016b6267ec7d1f54 to your computer and use it in GitHub Desktop.
Convert numeric to formatted string with cash unit by format
# frozen_string_literal: true
# Numeric
class Numeric
# convert numeric (integer or float)
# to formatted string with cash unit
#
# @example
# 42_000.to_cash '$', ',', '.', '%<unit>s%<amount>.2f' # => $42.000,00
# 42_000.42.to_cash 'RUB', ',', ' ', '%<amount>.2f %<unit>s' # => 42 000,42 RUB
#
# @param [String] unit
# @param [String] separator
# @param [String] delimiter
# @param [String] format
def to_cash(unit, separator, delimiter, format = '%<amount>.2f %<unit>s')
value = {
unit: unit,
amount: self
}
amount_formatted = format % value
amount_formatted = amount_formatted.gsub '.', separator
position = amount_formatted.match(separator).begin(0) - 3
until /[0-9]/.match(amount_formatted[position]).nil?
amount_formatted.insert position, delimiter
position -= 3
end
amount_formatted
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment