【问题标题】:Python : Show only necessary decimals [duplicate]Python:仅显示必要的小数[重复]
【发布时间】:2021-03-26 03:41:53
【问题描述】:

我希望 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 是一个整数,因为您将它硬编码为整数。但是如果x 是其他两个值之间某些操作的结果呢?如何区分整数结果和非常接近整数的浮点值?
  • @chepner,请理解,在制作计算器时,我不知道结果。计算后,我只想要所需的小数。以下答案有很好的区分相同点的方法。
  • 考虑x - 1x = 1.1x = 1.0 需要多少个小数位,仅基于x - 1结果,而不是知道什么是分配给x

标签: python python-3.x anaconda spyder anaconda3


【解决方案1】:

在打印之前检查它是否是一个浮点数呢?

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

【讨论】:

  • 如果x = 10.0怎么办?
  • 是的,你是对的,我更新了代码并将其添加到示例中,谢谢
  • 这是最简单的答案!
【解决方案2】:

检查数字是int还是float

这是我的第一个方法

  1. 使用 isinstance(内置函数)


number = input("Input number: ")


if  isinstance(number, int) == True:
    print(int(number))
else:
    print(number)

  1. 如果值存在小数点后
number = float(input("Input number: "))

number_dec = str(number-int(number))[1:]


if  number_dec == '.0':
    print(int(number))
else:
    print(number)

【讨论】:

    猜你喜欢
    • 2018-10-05
    • 2012-05-17
    • 1970-01-01
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    • 2020-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多