Formatting floats without trailing zeros

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

    Using the QuantiPhy package is an option. Normally QuantiPhy is used when working with numbers with units and SI scale factors, but it has a variety of nice number formatting options.

        >>> from quantiphy import Quantity
    
        >>> cases = '3 3. 3.0 3.1 3.14 3.140 3.14000'.split()
        >>> for case in cases:
        ...    q = Quantity(case)
        ...    print(f'{case:>7} -> {q:p}')
              3 -> 3
             3. -> 3
            3.0 -> 3
            3.1 -> 3.1
           3.14 -> 3.14
          3.140 -> 3.14
        3.14000 -> 3.14
    

    And it will not use e-notation in this situation:

        >>> cases = '3.14e-9 3.14 3.14e9'.split()
        >>> for case in cases:
        ...    q = Quantity(case)
        ...    print(f'{case:>7} -> {q:,p}')
        3.14e-9 -> 0
           3.14 -> 3.14
         3.14e9 -> 3,140,000,000
    

    An alternative you might prefer is to use SI scale factors, perhaps with units.

        >>> cases = '3e-9 3.14e-9 3 3.14 3e9 3.14e9'.split()
        >>> for case in cases:
        ...    q = Quantity(case, 'm')
        ...    print(f'{case:>7} -> {q}')
           3e-9 -> 3 nm
        3.14e-9 -> 3.14 nm
              3 -> 3 m
           3.14 -> 3.14 m
            3e9 -> 3 Gm
         3.14e9 -> 3.14 Gm
    

提交回复
热议问题