1

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.

4 Answers 4

5
yourVar = "Total of the sale is: ${:,.2f}".format(TotalAmount)
Sign up to request clarification or add additional context in comments.

Comments

0

Just save it to a variable, instead of passing it to print.

>>> dog = "doggy"
>>> pets = "cat and %s" % dog
>>> print pets
cat and doggy

Comments

0

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

Comments

0

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.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.