decimal string output drops trailing zeros #19989
|
I have been testing the decimal module for handling dollar amounts. The default string representation doesn't include any trailing zeros making it difficult to line up in columns. Until I find a better solution this code takes care of the alignment: |
Replies: 1 comment 2 replies
|
That library drops them by design: For money it's simpler to go through whole cents, which also rounds the last digit instead of cutting it off ( def money(n, places=2):
q = (abs(n) * (10 ** places)).to_int_round()
s = str(q)
if places:
s = "0" * (places + 1 - len(s)) + s
s = s[:-places] + "." + s[-places:]
return ("-" if q and n < DecimalNumber(0) else "") + sI ran it on the unix port of current MicroPython master with the library from that repo: |
That library drops them by design:
DecimalNumberkeeps the digits as one integer plus a count of decimals and trims trailing zeros, soDecimalNumber("64000.00")holds64000and prints64000. It has no method that prints a fixed number of places;to_string_thousands()andto_string_max_length()leave the zeros off too.For money it's simpler to go through whole cents, which also rounds the last digit instead of cutting it off (
fix_trailing()truncates, so2.675comes out as2.67):