如何在python中将浮点数打印到用户指定值的小数位

时间:2017-12-15 18:55:54

标签: python

我的代码,

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))))

这是我到目前为止所想要的,并且打印出用户输入值的小数位的答案,比如他们想要转换42.78华氏度我希望给出答案为{{ 1}}

2 个答案:

答案 0 :(得分:3)

您可以使用round()来更轻松地指定小数位:

>>> round(1.23234, 2)
1.23

因此,要将此应用于您的代码,您需要先将其输入存储为string,这样您就可以确定要舍入的数量,然后在最后进行舍入:

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])))

当我进入时:

count <== 1
value <== 567.123

给出了正确的结果:

297.291

答案 1 :(得分:0)

如果我想保留用户的精确值,包括小数点以外的位数,我会使用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