Currency formatting in Python
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Puzzle3
--
Chapters
00:00 Currency Formatting In Python
00:12 Accepted Answer Score 279
00:32 Answer 2 Score 114
00:48 Answer 3 Score 58
01:23 Answer 4 Score 54
02:01 Answer 5 Score 27
02:20 Thank you
--
Full question
https://stackoverflow.com/questions/3209...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #formatting #currency
#avk47
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Puzzle3
--
Chapters
00:00 Currency Formatting In Python
00:12 Accepted Answer Score 279
00:32 Answer 2 Score 114
00:48 Answer 3 Score 58
01:23 Answer 4 Score 54
02:01 Answer 5 Score 27
02:20 Thank you
--
Full question
https://stackoverflow.com/questions/3209...
--
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 £