Formatting floats without trailing zeros

后端 未结 18 1563
再見小時候
再見小時候 2020-11-22 10:03

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:

<         


        
相关标签:
18条回答
  • 2020-11-22 10:43

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

    0 讨论(0)
  • 2020-11-22 10:43

    You can achieve that in most pythonic way like that:

    python3:

    "{:0.0f}".format(num)
    
    0 讨论(0)
  • 2020-11-22 10:45

    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.

    0 讨论(0)
  • 2020-11-22 10:45

    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.

    0 讨论(0)
  • 2020-11-22 10:46

    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'
    
    0 讨论(0)
  • 2020-11-22 10:47

    You can use max() like this:

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

    0 讨论(0)
提交回复
热议问题