py-money

0.5.0 · active · verified Mon Apr 13

py-money is a Python 3 library that provides `Money` and `Currency` classes for precise monetary calculations. It enforces correct decimal places for currencies, leverages Python's `Decimal` type to prevent floating-point errors, and supports basic arithmetic and logical operations for immutable money objects. The current version is 0.5.0, with releases historically focused on bug fixes and minor feature enhancements.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create `Money` objects, perform basic arithmetic operations, and work with currency subunits. It highlights the importance of using the correct import paths and shows how to access the amount and currency code.

from money.money import Money
from money.currency import USD, EUR

# Create Money objects
price_usd = Money('100.50', USD)
price_eur = Money('50.25', EUR)

# Accessing amount and currency
print(f"USD Price: {price_usd.amount} {price_usd.currency.code}") # Expected: USD Price: 100.50 USD

# Basic arithmetic (same currency)
total_usd = price_usd + Money('9.50', USD)
print(f"Total USD: {total_usd}") # Expected: Total USD: 110.00 USD

# Subtraction
remaining_usd = price_usd - Money('20.00', USD)
print(f"Remaining USD: {remaining_usd}") # Expected: Remaining USD: 80.50 USD

# Multiplication
taxed_price = price_usd * 1.05
print(f"Taxed USD: {taxed_price}") # Expected: Taxed USD: 105.53 USD (due to rounding)

# Division
split_price = price_usd / 2
print(f"Split USD: {split_price}") # Expected: Split USD: 50.25 USD

# Create from subunits (v0.3.0+)
# e.g., 12345 cents for USD
sub_unit_money = Money.from_sub_units(12345, USD)
print(f"From subunits USD: {sub_unit_money}") # Expected: From subunits USD: 123.45 USD
print(f"To subunits USD: {sub_unit_money.sub_units}") # Expected: To subunits USD: 12345

view raw JSON →