3

I want to output certain decimal variables with certain formatting, and my understanding is you do this with contexts from the decimal class. How would I go about doing this?

 x = decimal.Decimal(2000.0)

And now I want to print this in the format $2,000.00 How would I go about doing that with a context?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Jasonca1
  • 4,848
  • 6
  • 25
  • 42

3 Answers3

1
val = 2000
print("${:.2f}".format(float(val)))   # This outputs $2000.00 (no comma)

But to add to comma you simply add it between the colon and decimal like so:

print("${:,.2f}".format(float(val)))   # This outputs $2,000.00 (with comma)
money = 65434562338.89
print("${:,.2f}".format(float(money))) # Outputs: $65,434,562,338.89

The :.2f formats the output so that only 2 decimal places are displayed where :.3f will show 3 decimals like $2000.000 and so forth.

Potion
  • 785
  • 1
  • 14
  • 36
1

Try:

>>> "${:,.2f}".format(decimal.Decimal(2000))
'$2,000.00'

>>> "${:,.2f}".format(decimal.Decimal("2000.987"))
'$2,000.99'

>>> "${:,.2f}".format(decimal.Decimal("1000000.1"))
'$1,000,000.10'

>>> "${:,.2f}".format(decimal.Decimal("123456789123456789123456789.12345"))
'$123,456,789,123,456,789,123,456,789.12'
donkopotamus
  • 22,114
  • 2
  • 48
  • 60
0

Try locale module

Example code:

import locale

x = 2000.00
locale.setlocale( locale.LC_ALL, '' )
locale.currency( x )
locale.currency( x, grouping=True )

Output:

'$2,000.00'

Reference: Currency formatting in Python

Documentation: https://docs.python.org/2/library/locale.html

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • Changing the `locale` causes a global change in behaviour for all threads in a program simply to satisfy printing a number. – donkopotamus May 22 '18 at 04:34