Currency formatting in Python
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Drifting Through My Dreams
--
Chapters
00:00 Question
00:15 Accepted answer (Score 264)
00:35 Answer 2 (Score 111)
00:50 Answer 3 (Score 57)
01:25 Answer 4 (Score 50)
02:05 Thank you
--
Full question
https://stackoverflow.com/questions/3209...
Accepted answer links:
[locale]: https://docs.python.org/3/library/locale...
Answer 2 links:
http://docs.python.org/dev/whatsnew/2.7....
Answer 3 links:
[Babel]: http://babel.pocoo.org/
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #formatting #currency
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Drifting Through My Dreams
--
Chapters
00:00 Question
00:15 Accepted answer (Score 264)
00:35 Answer 2 (Score 111)
00:50 Answer 3 (Score 57)
01:25 Answer 4 (Score 50)
02:05 Thank you
--
Full question
https://stackoverflow.com/questions/3209...
Accepted answer links:
[locale]: https://docs.python.org/3/library/locale...
Answer 2 links:
http://docs.python.org/dev/whatsnew/2.7....
Answer 3 links:
[Babel]: http://babel.pocoo.org/
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #formatting #currency
#avk47
ACCEPTED ANSWER
Score 285
See the locale module.
This does currency (and date) formatting.
>>> import locale
>>> locale.setlocale( locale.LC_ALL, '' )
'English_United States.1252'
>>> locale.currency( 188518982.18 )
'$188518982.18'
>>> locale.currency( 188518982.18, grouping=True )
'$188,518,982.18'
ANSWER 2
Score 115
New in 2.7
>>> '{:20,.2f}'.format(18446744073709551616.0)
'18,446,744,073,709,551,616.00'
ANSWER 3
Score 58
Not quite sure why it's not mentioned more online (or on this thread), but the Babel package (and Django utilities) from the Edgewall guys is awesome for currency formatting (and lots of other i18n tasks). It's nice because it doesn't suffer from the need to do everything globally like the core Python locale module.
The example the OP gave would simply be:
>>> import babel.numbers
>>> import decimal
>>> babel.numbers.format_currency( decimal.Decimal( "188518982.18" ), "GBP" )
£188,518,982.18
ANSWER 4
Score 55
This is an ancient post, but I just implemented the following solution which:
- Doesn't require external modules
- Doesn't require creating a new function
- Can be done in-line
- Handles multiple variables
- Handles negative dollar amounts
Code:
num1 = 4153.53
num2 = -23159.398598
print 'This: ${:0,.0f} and this: ${:0,.2f}'.format(num1, num2).replace('$-','-$')
Output:
This: $4,154 and this: -$23,159.40
And for the original poster, obviously, just switch $ for £