Formatting floats in Python without superfluous ze

2019-01-01 06:57发布

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"

14条回答
公子世无双
2楼-- · 2019-01-01 07:46

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.

查看更多
爱死公子算了
3楼-- · 2019-01-01 07:46

You can use max() like this:

print(max(int(x), x))

查看更多
只若初见
4楼-- · 2019-01-01 07:51

For float you could use this:

def format_float(num):
    return ('%i' if num == int(num) else '%s') % num

Test it:

>>> format_float(1.00000)
'1'
>>> format_float(1.1234567890000000000)
'1.123456789'

For Decimal see solution here: https://stackoverflow.com/a/42668598/5917543

查看更多
君临天下
5楼-- · 2019-01-01 07:53

You can achieve that in most pythonic way like that:

python3:

"{:0.0f}".format(num)
查看更多
若你有天会懂
6楼-- · 2019-01-01 07:54
>>> str(a if a % 1 else int(a))
查看更多
一个人的天荒地老
7楼-- · 2019-01-01 07:58

What about trying the easiest and probably most effective approach? The method normalize() removes all the rightmost trailing zeros.

from decimal import Decimal

print (Decimal('0.001000').normalize())
# Result: 0.001

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:

from decimal import Decimal


def format_float(f):
    d = Decimal(str(f));
    return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
查看更多
登录 后发表回答