开发者

Python - Add Formatted Number To String

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 str开发者_开发百科ing?

Thanks for any help.


yourVar = "Total of the sale is: ${:,.2f}".format(TotalAmount)


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

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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜