Question

How can i print a variable whose value is a floting number?

Eg.

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

Why is the return 1 instead of 1.75, and how can i change it?

Was it helpful?

Solution 2

You should use %f instead:

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

To specify a certain precision, you do it as:

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.

OTHER TIPS

Because in string formatting, just like in C, %d gives an integer.

To fix it, you need to use %f instead of %d:

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

You are using %d for displaying a floating point number. You can try below methods for displaying floating point numbers with precision. Method 2 is preferred for python 3 and above

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top