Python change repr floating digits

后端 未结 2 1265
灰色年华
灰色年华 2021-01-15 00:00

Okay, I want to use repr() to print out a text version of a bunch of lists and nested arrays.

But I want the numbers to have only 4 decimal places not: 42.7635745114

相关标签:
2条回答
  • 2021-01-15 00:11

    Maybe you could try string formatting using return "%.4f" %(self.float):

    >>> class obj:
    ...     def __init__(self, value):
    ...             self.float = value
    ...     def __repr__(self):
    ...             return "%.4f" %(self.float)
    ... 
    >>> x = obj(8.1231231253252)
    >>> x.float
    8.1231231253252
    >>> x
    8.1231
    >>> 
    
    0 讨论(0)
  • 2021-01-15 00:26

    No, there is no way to overload repr(). The format for floats is hardcoded in the C source code.

    The float_repr() function calls a helper function with the 'r' formatter, which eventually calls a utility function that hardcodes the format to what comes down to format(float, '.16g').

    You could subclass float, but to only do that for representing values (especially in a larger structure) is overkill. This is where repr (reprlib in Python 3) comes in; that library is designed to print useful representations of arbitrary data structures, and letting you hook into printing specific types in that structure.

    You could use the repr module by subclassing repr.Repr(), providing a repr_float() method to handle floats:

    try:  # Python 3
        import reprlib
    except ImportError:  # Python 2
        import repr as reprlib
    
    class FloatRepr(reprlib.Repr):
        def repr_float(self, value, level):
            return format(value, '.4f')
    
    print(FloatRepr().repr(object_to_represent))
    

    Demo:

    >>> import random
    >>> import reprlib
    >>> class FloatRepr(reprlib.Repr):
    ...     def repr_float(self, value, level):
    ...         return format(value, '.4f')
    ... 
    >>> print(FloatRepr().repr([random.random() for _ in range(5)]))
    [0.5613, 0.9042, 0.3891, 0.7396, 0.0140]
    

    You may want to set the max* attributes on your subclass to influence how many values are printed per container type.

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