How can I format a decimal to always show 2 decimal places?

前端 未结 12 2109
有刺的猬
有刺的猬 2020-11-22 17:31

I want to display:

49 as 49.00

and:

54.9 as 54.90

Regardless of the length of the decimal

12条回答
  •  醉梦人生
    2020-11-22 17:46

    You can use the string formatting operator as so:

    num = 49
    x = "%.2f" % num  # x is now the string "49.00"
    

    I'm not sure what you mean by "efficient" -- this is almost certainly not the bottleneck of your application. If your program is running slowly, profile it first to find the hot spots, and then optimize those.

提交回复
热议问题