Formatting floats without trailing zeros

后端 未结 18 1793
再見小時候
再見小時候 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: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.

提交回复
热议问题