想通过Json输出一个嵌套的字典数据数据结构,其中的浮点数位数比较长,找不到合适的方法对小数点之后数字进行截断。
数据结构示例:
import json
from json import encoder
data = {
"branch": "xxxx",
"date": "2022-11-10",
"achv": 10759.900000000001
}
class MyEncoder(json.JSONEncoder):
def encode(self, obj):
if isinstance(obj, float):
return format(obj, '.1f')
return json.JSONEncoder.encode(self, obj)
json_str = json.dumps(data, cls=MyEncoder)
print(json_str)
# 输出
# {"branch": "xxxx", "date": "2022-11-10", "achv": 10759.900000000001}
下面的链接中都提到了这个问题,但没有彻底解决。
参考链接: