Module: Jekyll::Unirate::Formatter
- Defined in:
- lib/jekyll/unirate/formatter.rb
Overview
Lightweight currency formatter. Ruby’s stdlib has no locale-aware money formatting and we deliberately avoid a heavy dependency (e.g. the ‘money` gem) for a static-site helper, so this is a pragmatic symbol table plus fixed grouping: `#,##0.00` with the symbol prefixed (or the ISO code when the symbol is unknown). Good enough for prices on a static page; not a substitute for full i18n.
Constant Summary collapse
- SYMBOLS =
{ "USD" => "$", "EUR" => "€", "GBP" => "£", "JPY" => "¥", "CNY" => "¥", "AUD" => "A$", "CAD" => "C$", "CHF" => "CHF ", "HKD" => "HK$", "NZD" => "NZ$", "SEK" => "kr ", "KRW" => "₩", "SGD" => "S$", "NOK" => "kr ", "MXN" => "MX$", "INR" => "₹", "RUB" => "₽", "ZAR" => "R", "TRY" => "₺", "BRL" => "R$", "TWD" => "NT$", "DKK" => "kr ", "PLN" => "zł ", "THB" => "฿", "IDR" => "Rp", "HUF" => "Ft ", "CZK" => "Kč ", "ILS" => "₪", "PHP" => "₱", "AED" => "د.إ ", "SAR" => "ر.س ", "MYR" => "RM", "RON" => "lei ", "NGN" => "₦", "BTC" => "₿" }.freeze
- ZERO_DECIMAL =
Currencies conventionally shown without decimal places.
%w[JPY KRW HUF IDR CLP VND ISK].freeze
Class Method Summary collapse
-
.format(amount, currency, decimals: nil) ⇒ Object
Format
amountincurrency. -
.group(value, decimals) ⇒ Object
Group a non-negative decimal with thousands separators and fixed decimals.
Class Method Details
.format(amount, currency, decimals: nil) ⇒ Object
Format amount in currency. Returns a String such as “€1,234.50”.
33 34 35 36 37 38 39 40 41 42 |
# File 'lib/jekyll/unirate/formatter.rb', line 33 def format(amount, currency, decimals: nil) currency = currency.to_s.upcase decimals ||= ZERO_DECIMAL.include?(currency) ? 0 : 2 rounded = BigDecimal(amount.to_s).round(decimals) sign = rounded.negative? ? "-" : "" number = group(rounded.abs, decimals) symbol = SYMBOLS[currency] # Sign goes outside the symbol ("-$1,234.50"), the conventional form. symbol ? "#{sign}#{symbol}#{number}" : "#{sign}#{number} #{currency}" end |
.group(value, decimals) ⇒ Object
Group a non-negative decimal with thousands separators and fixed decimals. Calls Kernel.format explicitly — the bareword ‘format` would resolve to this module’s own currency-formatting method.
47 48 49 50 51 |
# File 'lib/jekyll/unirate/formatter.rb', line 47 def group(value, decimals) whole, frac = Kernel.format("%.#{decimals}f", value).split(".") whole = whole.reverse.gsub(/(\d{3})(?=\d)/, '\1,').reverse frac ? "#{whole}.#{frac}" : whole end |