Add money.py, a class I'd like to start using in here instead of floats.
[retire.git] / utils.py
1
2 # Global helper functions
3 def truncate(n, decimals=2):
4     """Truncate a float to a particular number of decimals."""
5     assert decimals > 0 and decimals < 10, "Decimals is weird"
6     multiplier = 10 ** decimals
7     return int(n * multiplier) / multiplier
8
9 def format_money(number):
10     """Format a monetary amount with a $ and comma thousands separators."""
11     return ("${:,}".format(truncate(number)))
12
13 def format_rate(rate):
14     """Format a multiplier nee rate to look nice."""
15     if rate >= 1.0:
16         return format_rate(rate - 1.0)
17     else:
18         return "{:<}%".format(round(rate * 100, 3))