【问题标题】:How to show only trailing decimals if they are all not zeros?如果它们都不为零,如何仅显示尾随小数?
【发布时间】:2019-11-26 11:00:33
【问题描述】:

我想将小数的值转换为字符串,但仅在尾随小数不全为零时才显示。例如 nice_decimal_show(Decimal("3.00")) == "3" nice_decimal_show(Decimal("3.14")) == "3.14"

这样做的规范方法是什么?

我现在正在做:

format_decimal_to_integer_string_if_possible(Decimal("3.000")) "3" >;>;>; format_decimal_to_integer_string_if_possible(Decimal("3.400")) "3.400" """ assert isinstance(decimal, Decimal) integral = decimal.to_integral() if integral == decimal: return str(integral) else: return str(decimal) ```

【问题讨论】:

  • 那个代码是什么?它不是有效的 python。

标签: python string decimal


【解决方案1】:

最好的方法是使用g 格式,而不是f 格式。这将抑制尾随小数零。例如:

>>> print("%g" % 3.0)
3
>>> 
>>> print("%g" % 3.0012)
3.0012
>>> 

您也可以在format 字符串中使用g

>>> print("{:g}".format(3.0))
3
>>> 
>>> print("{:g}".format(3.0012))
3.0012
>>> 

如果要限制精度,可以使用:

>>> print("%.4g" % 3.0012)
3.001
>>> 

>>> print("{:.4g}".format(3.0012))
3.001
>>>  

【讨论】:

    【解决方案2】:

    我喜欢这种方式:

    ('%f' % Decimal("3.000")).rstrip('0').rstrip('.')
    

    我不知道这是否是规范的做法......

    【讨论】:

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