Change default float print format

后端 未结 7 534
无人共我
无人共我 2020-12-01 16:44

I\'ve some lists and more complex structures containing floats. When printing them, I see the floats with a lot of decimal digits, but when printing, I don\'t need all of th

相关标签:
7条回答
  • 2020-12-01 16:52

    If you are using C language, you can either use #define or "%*.*f" to do that, e.g.

    printf("%*.*f",4,2,variable);
    
    0 讨论(0)
  • 2020-12-01 16:54

    No, because that would require modifying float.__str__(), but you aren't allowed to monkeypatch C types. Use string interpolation or formatting instead.

    0 讨论(0)
  • 2020-12-01 17:01

    Upgrade to Python 3.1. It doesn't use more digits than necessary.

    Python 3.1.2 (r312:79147, Apr 15 2010, 15:35:48) 
    [GCC 4.4.3] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> 0.1
    0.1
    
    0 讨论(0)
  • 2020-12-01 17:10

    You are not allowed to monkeypatch C types, like Ignacio said.

    However, if you are terribly pressed in doing so and you know some C, you could go modify the Python interpreter source code yourself, then recompile it into a custom solution. Once I modified one of the standard behaviors for lists and it was only a moderate pain.

    I suggest you find a better solution, such as just printing the floats with the "%0.2f" printf notation:

    for item in mylist:
        print '%0.2f' % item,
    

    or

    print " ".join('%0.2f' % item for item in mylist)
    
    0 讨论(0)
  • 2020-12-01 17:12

    This doesn't answer the more general question of floats nested in other structures, but if you just need to print floats in lists or even array-like nested lists, consider using numpy.

    e.g.,

    import numpy as np
    np.set_printoptions(precision=3, suppress=False)
    list_ = [[1.5398, 2.456, 3.0], 
             [-8.397, 2.69, -2.0]]
    print(np.array(list_))
    

    gives

    [[ 1.54   2.456  3.   ]
     [-8.397  2.69  -2.   ]]
    
    0 讨论(0)
  • 2020-12-01 17:13
    >>> a = 0.1
    >>> a
    0.10000000000000001
    >>> print a
    0.1
    >>> print "%0.3f" % a
    0.100
    >>>
    

    From the Python docs, repr(a) would give 17 digits (as seen by just typing a at the interactive prompt, but str(a) (automatically performed when you print it) rounds to 12.

    Edit: Most basic hack solution... You have to use your own class though, so...yeah.

    >>> class myfloat(float):
    ...     def __str__(self):
    ...             return "%0.3f" % self.real
    >>> b = myfloat(0.1)
    >>> print repr(b)
    0.10000000000000001
    >>> print b
    0.100
    >>>
    
    0 讨论(0)
提交回复
热议问题