Created
November 2, 2018 11:10
-
-
Save tit/6ef0012603868ffc016b6267ec7d1f54 to your computer and use it in GitHub Desktop.
Convert numeric to formatted string with cash unit by format
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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