Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Friendly Formatting #88

Open
dvf opened this issue Oct 22, 2021 · 1 comment
Open

Friendly Formatting #88

dvf opened this issue Oct 22, 2021 · 1 comment

Comments

@dvf
Copy link

dvf commented Oct 22, 2021

Firstly, this is a fantastic library.

I have a few questions relating to readability of the string output:

  • Is it possible to print 1000000.00 USD as 1,000,000.00 USD? (humanize.intcomma module does this)
  • Is there a way to print $1000.00 instead of 1000.00 USD?
  • Is there a way to strip nanos if they're zeroes? 1000.00 USD -> 1000 USD?
@whiskeyriver
Copy link

whiskeyriver commented Mar 21, 2024

@dvf

I just came across this library, and even though this question is old I'll answer this in case someone else stumbles across it.

Caveat: Below I give 2 ways to do this using only Python's stdlib. However the locale module is not threadsafe. If you deal with dynamic locales then check out Babel.

Formatting the Money using regular money format

Python's string formatting will handle number grouping:

value = Money("1234567.86", Currency.USD)
f"${value.amount:,}"

Output: '$1,234,567.86'

If you want to use a locale-aware separator just specify n instead of ,:

import locale

locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8')

value = Money("1234567.86", Currency.EUR)
f"{value.amount:n} €"

Output: '1.234.567,86 €'

It's easier to read if you use the locale module's built-in currency handler:

locale.currency(value.amount, symbol=True, grouping=True)

Output: '1.234.567,86 €'

Truncate to an integer if modulo 1 == 0

I struggle to see the use case for this question.

Keep in mind that if you use the locale.currency method for formatting (or probably any currency helper) then you'd always get a decimal output. This means you would need to use string-formatting and handle locale specifics manually.

def maybe_truncate(value: Money) -> int | Decimal:
    if value % 1 == 0:
        return int(value)
    return value.as_decimal()

value = Money("1234567.86", Currency.USD)
f"${maybe_truncate(value):n}"
-> $1,234,567.86

value += 0.14
f"${maybe_truncate(value):n}"
-> $1,234,568

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants