【问题标题】:How to isolate a single digit in a decimal?如何隔离小数中的单个数字?
【发布时间】:2021-07-18 01:21:22
【问题描述】:

我正在尝试隔离小数内的单个数字以显示格式化的百分比。

我得到:

result = 8 / 10
print(result)
#Output: 0.8

我想单独隔离 8 以便我可以打印:

print(f"The answer is {result}%")
#Output: The answer is 80%

我该怎么做?

【问题讨论】:

标签: python python-3.x


【解决方案1】:

你的意思是去掉“0.”吗? 如果是这样,您可以使用:

print(str(result * 100) + '%')

附: 0.8 表示 80%,而不是 8%。

【讨论】:

  • 是的,这是有道理的。我想我只是在为一个简单的解决方案寻找一个过于复杂的答案。
  • 有时候我们就是找不到简单的解决方案?Python之禅真的很有意义?There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch.
【解决方案2】:

首先,0.8 是 80% 而不是 8%。

将小数格式化为百分比使用print(f'{result:.0%}'),这将产生80%

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-17
    • 2016-11-27
    • 2023-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-06
    相关资源
    最近更新 更多