-2

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?

  • The string format argument you're using `%d` is for use in (decimal) integer numbers. Use `%f` instead. – Ffisegydd May 12 '14 at 15:12
  • Just because it can be fixed with one letter doesn't mean that it was a typo. This should not have been closed. It is a genuine problem that can be reproduced? Yes. Was it a typo? No, it was caused by not yet knowing a piece of relevant programming information. I'd say this is perfectly on-topic and should be re-opened. – anon582847382 May 12 '14 at 18:20

3 Answers3

4

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."
anon582847382
  • 19,907
  • 5
  • 54
  • 57
3

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.
sshashank124
  • 31,495
  • 9
  • 67
  • 76
2

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)

sajadkk
  • 764
  • 1
  • 5
  • 19