How would I print float to decimal of user specified value in python

My code

print ("Welcome to the Imperial to Metric converter")

choice = int(input("For Fahrenheit to Celsius press 1, Feet to Meters press 2, Pounds to Kilograms press 3: "))

if choice != 1 and 2 and 3:
  print ("Choose a valid function")
else:
  value = float(input("Select the value you wish to convert: "))
  def convert(value):
    if choice == 1:
      return (value - 32) * (5/9)
    elif choice == 2:
      return value / 3.2808
    elif choice == 3:
      return value  / 2.2046

  print ("%.2f" %(float(convert(value))))

This is what I still have, and would like to print the answer to any decimal place that the user put, like, say, they wanted to convert 42.78Fahrenheit. I would like to give an answer asxx.xx

+4
source share
2 answers

You can use round()one that will make it easier for you to specify decimals:

>>> round(1.23234, 2)
1.23

So, to apply this to your code, you first need to save them as stringso that you can determine how many rounds to round to, and then round at the end:

print ("Welcome to the Imperial to Metric converter")

choice = int(input("For Fahrenheit to Celsius press 1, Feet to Meters press 2, Pounds to Kilograms press 3: "))

if choice not in (1, 2, 3):
  print ("Choose a valid function")
else:
  s = input("Select the value you wish to convert: ")
  value = float(s)
  def convert(value):
    if choice == 1:
      return (value - 32) * (5/9)
    elif choice == 2:
      return value / 3.2808
    elif choice == 3:
      return value  / 2.2046

 print(round(float(convert(value)), len(s.split(".")[1])))

which when entering:

count <== 1
value <== 567.123

gave the correct result:

297.291
+3
source

, , decimal.Decimal decimal.Decimal.quantize().

from decimal import Decimal

def convert(value):
    if choice == 1:
        return (value - 32) * 5/9
    elif choice == 2:
        return value / 32808 * 10000
    elif choice == 3:
        return value / 22046 * 10000

choice = 1
value = Decimal(input("Select the value you wish to convert: "))
print("%s" % (convert(value).quantize(value)))

:

$ python3 x.py 
Select the value you wish to convert: 32
0
$ python3 x.py 
Select the value you wish to convert: 32.000
0.000
$ 

, , . Decimal float.

0

Source: https://habr.com/ru/post/1690873/


All Articles