Reputation: 18685
Using Python v2, I have the following code:
print ("Total of the sale is: ${:,.2f}".format(TotalAmount))
This is taking the string called "TotalAmount" and formatting it so that it looks like this: $100.00, ie: a monetary value, no matter what the number is.
Is there a way to write the formatted output to a string?
Thanks for any help.
Upvotes: 1
Views: 2180
Reputation: 4728
TotalAmount should be a number (either int
, float
or Decimal
), not a string, when you use f
type formatting. Your print statement is fine, although the parens are not needed in Python ver 2.x, but in this case they are OK as they are considered to be part of the print statement's single expression. (Also a good idea for possible future upgrade to ver 3.x.)
Upvotes: 0
Reputation: 37919
Try this to format with 2 digits after decimal pt:
for amt in (123.45, 5, 100):
val = "Total of the sale is: $%0.2f" % amt
print val
Total of the sale is: $123.45
Total of the sale is: $5.00
Total of the sale is: $100.00
Upvotes: 0
Reputation: 56694
yourVar = "Total of the sale is: ${:,.2f}".format(TotalAmount)
Upvotes: 5
Reputation: 4865
Just save it to a variable, instead of passing it to print.
>>> dog = "doggy"
>>> pets = "cat and %s" % dog
>>> print pets
cat and doggy
Upvotes: 0