How to format a float so it does not containt the remaing zeros? In other words, I want the resulting string to be as short as possible..?
Like:
3 -> "3"
3. -> "3"
3.0 -> "3"
3.1 -> "3.1"
3.14 -> "3.14"
3.140 -> "3.14"
How to format a float so it does not containt the remaing zeros? In other words, I want the resulting string to be as short as possible..?
Like:
3 -> "3"
3. -> "3"
3.0 -> "3"
3.1 -> "3.1"
3.14 -> "3.14"
3.140 -> "3.14"
While formatting is likely that most Pythonic way, here is an alternate solution using the
more_itertools.rstrip
tool.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
.You can use
max()
like this:print(max(int(x), x))
For float you could use this:
Test it:
For Decimal see solution here: https://stackoverflow.com/a/42668598/5917543
You can achieve that in most pythonic way like that:
python3:
What about trying the easiest and probably most effective approach? The method normalize() removes all the rightmost trailing zeros.
Works in Python 2 and Python 3.
-- Updated --
The only problem as @BobStein-VisiBone pointed out, is that numbers like 10, 100, 1000... will be displayed in exponential representation. This can be easily fixed using the following function instead: