在python中打印浮点

时间:2014-05-12 15:11:25

标签: python variables printing point floating

如何打印值为浮点数的变量?

例如

my_height = 1.75 #meters
print "I'm %s meters tall." % my_height

为什么返回1而不是1.75,我该如何改变呢?

3 个答案:

答案 0 :(得分:4)

因为在字符串格式中,就像在C中一样,%d给出一个整数。

要解决此问题,您需要使用%f代替%d

print "I'm %f meters tall." % my_height
# Outputs "I'm 1.75 meters tall."

答案 1 :(得分:3)

您应该使用%f代替:

my_height = 1.75 #meters
>>> print "I'm %f meters tall." % my_height
I'm 1.750000 meters tall.

要指定特定精度,请执行以下操作:

my_height = 1.75 #meters
>>> print "I'm %.2f meters tall." % my_height   #the 2 denoting two figures after decimal point
I'm 1.75 meters tall.

答案 2 :(得分:2)

您正在使用%d来显示浮点数。您可以尝试以下方法精确显示浮点数。对于python 3及更高版本

,方法2是首选

方法1: print "I'm %.2f meters tall." % my_height

方法2: print "I'm {:.2f} meters tall.".format(my_height)