통화 포맷터
USD, EUR, JPY, GBP, KRW 등 다양한 통화 형식으로 숫자를 표시합니다.
자주 묻는 질문
코드 구현
import locale
def format_currency_python(amount, currency_code="USD", locale_str="en_US"):
"""
Format a number as a currency string using Python's locale module.
Note: locale must be installed on the system.
"""
try:
locale.setlocale(locale.LC_ALL, locale_str + ".UTF-8")
return locale.currency(amount, symbol=True, grouping=True)
except locale.Error:
return f"{currency_code} {amount:,.2f}"
# Using the babel library (recommended for production)
# pip install babel
try:
from babel.numbers import format_currency
examples = [
(1234567.89, "USD", "en_US"),
(1234567.89, "EUR", "de_DE"),
(1234567, "JPY", "ja_JP"),
(1234567.89, "GBP", "en_GB"),
(1234567.89, "INR", "en_IN"),
(1234567.89, "BRL", "pt_BR"),
]
print("Locale-aware currency formatting with Babel:")
for amount, currency, loc in examples:
formatted = format_currency(amount, currency, locale=loc)
print(f" {loc:8} {currency}: {formatted}")
except ImportError:
# Fallback without Babel
numbers = [1234567.89, 1000, 0.50]
for n in numbers:
print(f"USD: ${n:>12,.2f}")
print(f"EUR: {n:>12,.2f} EUR")
Comments & Feedback
Comments are powered by Giscus. Sign in with GitHub to leave a comment.