简体   繁体   中英

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"

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. 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:

>>> 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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM