Python : 只显示必要的小数
Python : Show only necessary decimals
我希望 python 只显示实际需要的小数位。例如:
x = 10
print("The value of 'x' is - " + float(x))
只会打印:
The value of 'x' is - 10.0
这真的很烦人,因为我正在尝试制作一个在很多地方使用 float()
的计算器,但我似乎无法摆脱 .0
.
我正在寻找一个非常简单的代码。而且,我不希望数字以任何方式四舍五入,从而改变原始的准确值。
我正在使用 Anaconda Spyder (Python 3.8),我将 运行 Anaconda Prompt 上的代码。
在打印之前检查它是否是一个浮动怎么样?
x = 10
y= int(x) if int(x)==x else float(x)
print("The value of 'x' is - " + str(y))
示例:
x = 10
y= int(x) if int(x)==x else float(x)
>>> print("The value of 'x' is - " + str(y))
The value of 'x' is - 10
x = 10.32
y= int(x) if int(x)==x else float(x)
>>> print("The value of 'x' is - " + str(y))
The value of 'x' is - 10.32
x = 10.0
y= int(x) if int(x)==x else float(x)
>>> print("The value of 'x' is - " + str(y))
The value of 'x' is - 10
检查数字是整型还是浮点型
这是我的第一个方法
- 使用 isinstance(内置函数)
number = input("Input number: ")
if isinstance(number, int) == True:
print(int(number))
else:
print(number)
- 如果值存在于小数点后
number = float(input("Input number: "))
number_dec = str(number-int(number))[1:]
if number_dec == '.0':
print(int(number))
else:
print(number)
我希望 python 只显示实际需要的小数位。例如:
x = 10
print("The value of 'x' is - " + float(x))
只会打印:
The value of 'x' is - 10.0
这真的很烦人,因为我正在尝试制作一个在很多地方使用 float()
的计算器,但我似乎无法摆脱 .0
.
我正在寻找一个非常简单的代码。而且,我不希望数字以任何方式四舍五入,从而改变原始的准确值。
我正在使用 Anaconda Spyder (Python 3.8),我将 运行 Anaconda Prompt 上的代码。
在打印之前检查它是否是一个浮动怎么样?
x = 10
y= int(x) if int(x)==x else float(x)
print("The value of 'x' is - " + str(y))
示例:
x = 10
y= int(x) if int(x)==x else float(x)
>>> print("The value of 'x' is - " + str(y))
The value of 'x' is - 10
x = 10.32
y= int(x) if int(x)==x else float(x)
>>> print("The value of 'x' is - " + str(y))
The value of 'x' is - 10.32
x = 10.0
y= int(x) if int(x)==x else float(x)
>>> print("The value of 'x' is - " + str(y))
The value of 'x' is - 10
检查数字是整型还是浮点型
这是我的第一个方法
- 使用 isinstance(内置函数)
number = input("Input number: ")
if isinstance(number, int) == True:
print(int(number))
else:
print(number)
- 如果值存在于小数点后
number = float(input("Input number: "))
number_dec = str(number-int(number))[1:]
if number_dec == '.0':
print(int(number))
else:
print(number)