|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +""" |
| 4 | +File: formats.py |
| 5 | +Various specialized string display formatting utilities. |
| 6 | +Test me with canned self-test or command-line argumnets. |
| 7 | +To do: add parans for negative money, and more feature. |
| 8 | +""" |
| 9 | + |
| 10 | + |
| 11 | +def commas(N): |
| 12 | + """ |
| 13 | + Format positive integer-like N for display with |
| 14 | + commas between digits grouping: "XXX,YYY,ZZZ" |
| 15 | + """ |
| 16 | + digits = str(N) |
| 17 | + assert(digits.isdigit()) |
| 18 | + result = '' |
| 19 | + while digits: |
| 20 | + digits, last3 = digits[:-3], digits[-3:] |
| 21 | + result = (last3 + ',' + result) if result else last3 |
| 22 | + return result |
| 23 | + |
| 24 | + |
| 25 | +def money(N, numwidth=0, currency="$"): |
| 26 | + """ |
| 27 | + Format number N for display with commas, 2 decimal digits, |
| 28 | + leading $ and sign, and optional padding: "$ -xxx,yyy.zz". |
| 29 | + numwidth=0 for no space padding, currency='' to omit symbol, |
| 30 | + and non-ASCII for others (e.g., pound=u'\xA3' or u'\u00A3'). |
| 31 | + """ |
| 32 | + sign = '-' if N < 0 else '' |
| 33 | + N = abs(N) |
| 34 | + whole = commas(int(N)) |
| 35 | + fract = ('%2f' % N)[-2:] |
| 36 | + number = '%s%s.%s' % (sign, whole, fract) |
| 37 | + return '%s%*s' % (currency, numwidth, number) |
| 38 | + |
| 39 | +if __name__ == '__main__': |
| 40 | + def selftest(): |
| 41 | + tests = 0, 1 # fails -1, 1.23 |
| 42 | + tests += 12, 123, 1234, 12345, 123456, 1234567 |
| 43 | + tests += 2 ** 32, 2 ** 100 |
| 44 | + for test in tests: |
| 45 | + print(commas(test)) |
| 46 | + |
| 47 | + tests = 0, 1, -1, 1.23, 1., 1.2, 3.1341 |
| 48 | + tests += 12, 123, 1234, 12345, 123456, 1234567 |
| 49 | + tests += 2 ** 32, (2 ** 32 + .2342) |
| 50 | + tests += 1.2324, 1.2, 0.2345 |
| 51 | + tests += -1.242, -1.2, -15.2 |
| 52 | + tests += -(2 ** 32), -(2 ** 32 + 0.2324) |
| 53 | + tests += 2 ** 100, -(2 ** 100) |
| 54 | + for test in tests: |
| 55 | + print('%s [%s]' % (money(test, 17), test)) |
| 56 | + |
| 57 | + import sys |
| 58 | + if len(sys.argv) == 1: |
| 59 | + selftest() |
| 60 | + else: |
| 61 | + print(money(float(sys.argv[1]), int(sys.argv[2]))) |
0 commit comments