How can I format a float so that it doesn\'t contain trailing zeros? In other words, I want the resulting string to be as short as possible.
For example:
<
Me, I'd do ('%f' % x).rstrip('0').rstrip('.')
-- guarantees fixed-point formatting rather than scientific notation, etc etc. Yeah, not as slick and elegant as %g
, but, it works (and I don't know how to force %g
to never use scientific notation;-).
You can achieve that in most pythonic way like that:
python3:
"{:0.0f}".format(num)
You could use %g
to achieve this:
'%g'%(3.140)
or, for Python 2.6 or better:
'{0:g}'.format(3.140)
From the docs for format: g
causes (among other things)
insignificant trailing zeros [to be] removed from the significand, and the decimal point is also removed if there are no remaining digits following it.
While formatting is likely that most Pythonic way, here is an alternate solution using the more_itertools.rstrip tool.
import more_itertools as mit
def fmt(num, pred=None):
iterable = str(num)
predicate = pred if pred is not None else lambda x: x in {".", "0"}
return "".join(mit.rstrip(iterable, predicate))
assert fmt(3) == "3"
assert fmt(3.) == "3"
assert fmt(3.0) == "3"
assert fmt(3.1) == "3.1"
assert fmt(3.14) == "3.14"
assert fmt(3.140) == "3.14"
assert fmt(3.14000) == "3.14"
assert fmt("3,0", pred=lambda x: x in set(",0")) == "3"
The number is converted to a string, which is stripped of trailing characters that satisfy a predicate. The function definition fmt
is not required, but it is used here to test assertions, which all pass. Note: it works on string inputs and accepts optional predicates.
See also details on this third-party library, more_itertools.
Use %g with big enough width, for example '%.99g'. It will print in fixed-point notation for any reasonably big number.
EDIT: it doesn't work
>>> '%.99g' % 0.0000001
'9.99999999999999954748111825886258685613938723690807819366455078125e-08'
You can use max()
like this:
print(max(int(x), x))