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

Currency normalization #478

Open
szewczykmira opened this issue Mar 10, 2017 · 5 comments
Open

Currency normalization #478

szewczykmira opened this issue Mar 10, 2017 · 5 comments
Labels

Comments

@szewczykmira
Copy link

In my project I need to format currency so that it won't display digital decimals if they are equal to zero. Right now I'm doing it by replacing .00 to .## in current locale pattern and passing it as format to format_currency and setting currency_digits=False. It works like charm when price has 0 or 2 decimal digits, but I'm not sure how to handle prices with 3 decimal digits. Can I safely replace .00 with . + '#' * decimal_digits or it will cause problems I'm not aware of? Or maybe there is better solution for that?

@akx
Copy link
Member

akx commented Mar 30, 2017

Am I understanding this correctly:

  • If the value is integer, print no decimals
  • If the value is not integer, print as many decimals as the currency usually would

If so, you can adapt the innards of format_currency (though I admit being able to wholesale override the number of decimals would be handy):

from babel import Locale
from babel.numbers import decimal

def custom_format_currency(value, currency, locale):
    value = decimal.Decimal(value)
    locale = Locale.parse(locale)
    pattern = locale.currency_formats['standard']
    force_frac = ((0, 0) if value == int(value) else None)
    return pattern.apply(value, locale, currency=currency, force_frac=force_frac)

print(custom_format_currency('2.50', 'EUR', 'fi'))
print(custom_format_currency('2.00', 'EUR', 'fi'))

outputs

2,50 €
2 €

@akx akx added the question label Mar 30, 2017
@kdeldycke
Copy link
Contributor

@szewczykmira : That's more or less what I did with my unround_pattern() method from #90 (comment). I hack the default format pattern of a local to not let it truncate amounts with lots of decimals. I guess you can reuse it and tweak it to your own needs.

@kdeldycke
Copy link
Contributor

This is addressed by #494.

@igo
Copy link

igo commented Jun 7, 2020

@akx can this zero-stripping feature be added as an option to format_currency()

@picturedots
Copy link

Bumping this -- I have a use case where I sometimes want to display currency without any decimals, but not have a solution that requires a different format string for each locale.

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

No branches or pull requests

5 participants