【问题标题】:Python3 drop decimal places if not needed如果不需要,Python3 会删除小数位
【发布时间】:2021-09-19 06:53:45
【问题描述】:

我看到很多关于在 Python 3 中使用有限的小数位数格式化浮点数的答案,例如:

>>> "{:.4f}".format(3.14159265359)
'3.1416'

但这种格式会保留多余的尾随 0:

>>> "{:.4f}".format(3/4)
'0.7500'

我想要的是以一种很好的方式删除尾随零:

>>> "{:.4f??}".format(3/4)
'0.75'

使用g 格式似乎更接近于此,但它会将小数点前的数字计为总字段宽度的一部分,例如:

>>> "{:.4g}".format(3/4)
'0.75'

是完美的,但是:

>>> "{:.4g}".format(3.14159265359)
'3.142'

而不是所需的3.1416

为了澄清,整数(例如 0 单独)根本不应该有小数。

单独使用format 是否可行,还是我必须通过对格式化数字进行字符串操作来删除尾随零?

我研究的文档页面(除了搜索网络):https://docs.python.org/3/library/string.html#formatspec

【问题讨论】:

  • 所以你想要整数?
  • @anarchy 我希望整数完全去掉小数,但如果一个数字有小数,则在小数点后最多显示 4 位(这是.4f 会给我的)但没有尾随零(如果小数点后没有足够的数字,.4f 将用零填充)。
  • 用整数看看我的答案行得通吗?

标签: python python-3.x format


【解决方案1】:

要将浮点数转换为小数点后最多 N 位但不包含尾随0 的字符串,您可以使用round(),然后再转换为字符串。 p>

>>> str(round(3.14159265359, 4))
'3.1416'
>>> str(round(3/4, 4))
'0.75'
>>> str(round(17, 4))
'17'

【讨论】:

  • 这不适用于 17.0
  • @ThePyGuy 你是对的 :( 看起来我在round 的结果上回到了.rstrip
【解决方案2】:

我不确定裸字符串格式是否可行,但您可以这样做:

>>> a = 3/ 4
>>> "{:.{a}f}".format(a, a=min(len(str(a).split('.')[-1]), 4))
'0.75'
>>> a = 3.14159265359
>>> "{:.{a}f}".format(a, a=min(len(str(a).split('.')[-1]), 4))
'3.1416'
>>> 

或者为什么不rstrip

>>> a = 3 / 4
>>> "{:.4f}".format(a).rstrip("0")
'0.75'
>>> a = 3.14159265359
>>> "{:.4f}".format(a).rstrip("0")
'3.1416'
>>> 

Numpy 可以做得更好:

>>> import numpy as np
>>> np.format_float_positional(0.75, 4)
'0.75'
>>> np.format_float_positional(np.pi, 4)
'3.1416'
>>> 

【讨论】:

    【解决方案3】:

    我发帖后发现的一种方法是:

    print('{:.4f}.format(a).rstrip('.0') or '0')
    

    我仍然想知道是否可以更优雅。

    【讨论】:

    • rstrip('.0') 会将“5500.00”更改为“55”。我认为你想要.rstrip('0').rstrip('.')
    • 我添加了一个 numpy 解决方案,我猜这是最好的。
    【解决方案4】:

    您要查找的是round,对于该整数条件,您可以使用float.is_integer

    def func(x, digits):
        x = round(x, digits)
        return int(x) if float.is_integer(x) else x
    

    样品运行

    >>> func(3.14159265359, 4)
    3.1416
    >>> func(3.14000022, 4)
    3.14
    >>> func(3.000022, 4)
    3
    

    PS:如果需要,您可以将返回值转换为字符串类型。

    【讨论】:

    • 你也可以用float.is_integer(x) 代替x.is_integer() :)
    【解决方案5】:

    您可以使用round function 来完成这项工作。 round function 需要两个 parameters。 第一个是你想要四舍五入的floating number,第二个是你想要的number of places after decimal

    a=10/3
    print(round(a,4))
    

    这将返回3.3333

    a=3/4
    print(round(a,4))
    

    这将返回0.75

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多