簡體   English   中英

如果全都不為零,如何僅顯示尾隨小數?

[英]How to show only trailing decimals if they are all not zeros?

我想將小數的值轉換為字符串,但是如果它們不全為零,則僅顯示尾隨的小數。 例如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) ```

最好的方法是使用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
>>>  

我喜歡這種方式:

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

我不知道這是否是規范的做法...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM