0

i want to get answer like if i input value for height 1 feet,it should give 30.48 cm as output,i want only 2 values after decimal

while True:
            try:
                height  = float(input('\nEnter your height in feet:'))
            except ValueError:
                print("\nPlease enter only number")
            else:
                break
cm = (height*30.48)
print("\nYour height is  %d cm." % cm)
  • 2
    This would explain on how to proceed with formatting. https://stackoverflow.com/questions/2389846/python-decimals-format – Pasan Chamikara Jun 27 '19 at 15:00
  • 1
    You are using `%d` so it shows an integer. Use `%.2f` if you want to shows two decimals. Note that it will also show `x.00` if x is already a round number. – Guimoute Jun 27 '19 at 15:03
  • Also, consider taking a look at https://realpython.com/python-string-formatting/#3-string-interpolation-f-strings-python-36 – olinox14 Jun 27 '19 at 15:04

1 Answers1

1

There are many ways to solve this; but as far as I know using the .format-method with your string is the recommended way in Python 3.
It allows you to cut off the value or to round the value in a correct way (for example, as asked, with 2 decimals):

while True:
            try:
                height  = float(input('\nEnter your height in feet:'))
            except ValueError:
                print("\nPlease enter only number")
            else:
                break
cm = (height*30.48)
print("\nYour height is {} cm.".format(round(cm,2)))

You could also round the result itself before:

cm = round(height*30.48, 2)
print("\nYour height is {} cm.".format(cm))

or use the decimal definition in the brackets as follows:

cm = (height*30.48)
print("\nYour height is {:.2f} cm.".format(cm))
MariusG
  • 86
  • 5