Round off dict values to 2 decimals

前端 未结 6 1734
庸人自扰
庸人自扰 2021-01-16 11:29

I\'m having a hard time rounding off values in dicts. What I have is a list of dicts like this:

y = [{\'a\': 80.0, \'b\': 0.0786235, \'c\': 10.0, \'d\': 10.6         


        
6条回答
  •  执笔经年
    2021-01-16 11:50

    JSONEncoder uses repr, and repr prints floats with all their available precision. The only possible solutions are to inherit from JSONEncoder and round while actually converting the values to a string (which implies to copy and adapt some code from the json.encoder module), or else wrap the floats into your own type RoundedFloat and register a serializer for that. Also note that repr's behaviour depends on the Python version used.

    As often with non-obvious behaviour, the observation during debugging can trick you: print uses str(), and str() rounds at a certain point, unlike repr() which shows the naked ugliness of floating point maths.

    The proof is in the code:

    >>> class F(float):
    ...     def __str__(self): return "str"
    ...     def __repr__(self): return "repr"
    ...     
    ... 
    >>> print F(1)
    str
    >>> F(1)
    repr
    >>> repr(1-1e-15)
    '0.999999999999999'
    >>> str(1-1e-15)
    '1.0'
    

提交回复
热议问题