[英]How to show only trailing decimals if they are all not zeros?
I want to convert the value of a decimal to a string, but only show the trailing decimals if they're not all zeros. 我想将小数的值转换为字符串,但是如果它们不全为零,则仅显示尾随的小数。 eg nice_decimal_show(Decimal("3.00")) == "3" nice_decimal_show(Decimal("3.14")) == "3.14"
例如nice_decimal_show(Decimal("3.00")) == "3" nice_decimal_show(Decimal("3.14")) == "3.14"
What would be the canonical way of doing this? 这样做的规范方法是什么?
Right now I'm doing: 现在我正在做:
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) ```
The best way is to use g
formatting, rather than f
formatting. 最好的方法是使用g
格式,而不是f
格式。 This will suppress trailing fractional zeroes. 这将抑制尾随零。 For example: 例如:
>>> print("%g" % 3.0)
3
>>>
>>> print("%g" % 3.0012)
3.0012
>>>
You can also use g
in format
strings: 您还可以在format
字符串中使用g
:
>>> print("{:g}".format(3.0))
3
>>>
>>> print("{:g}".format(3.0012))
3.0012
>>>
If you want to limit the precision, you can use: 如果要限制精度,可以使用:
>>> print("%.4g" % 3.0012)
3.001
>>>
or 要么
>>> print("{:.4g}".format(3.0012))
3.001
>>>
I like this way of doing it: 我喜欢这种方式:
('%f' % Decimal("3.000")).rstrip('0').rstrip('.')
I don't know if it's the canonical way of doing it though... 我不知道这是否是规范的做法...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.