在python json.dumps输出中禁用科学计数法 [英] Disable scientific notation in python json.dumps output

查看:388
本文介绍了在python json.dumps输出中禁用科学计数法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

json.dumps使用科学计数法输出较小的浮点或十进制值,这对于将输出发送到的json-rpc应用程序是不可接受的.

json.dumps outputs small float or decimal values using scientific notation, which is unacceptable to the json-rpc application this output is sent to.

>>> import json
>>> json.dumps({"x": 0.0000001})
'{"x": 1e-07}'

我想要此输出:

'{"x": 0.0000001}'

最好避免引入其他依赖项.

It would be ideal to avoid introducing additional dependencies.

推荐答案

一种格式化方式

evil = {"x": 0.00000000001}

是窃取Decimal的"f"格式化程序.这是我发现的唯一避免裁切问题和指数的简便方法,但这空间效率低.

is to steal Decimal's "f" formatter. It's the only easy way I've found that avoids both cropping problems and exponents, but it's not space efficient.

class FancyFloat(float):
    def __repr__(self):
        return format(Decimal(self), "f")

要使用它,您可以使编码器对输入进行十进制"

To use it you can make an encoder that "decimalize"s the input

class JsonRpcEncoder(json.JSONEncoder):
    def decimalize(self, val):
        if isinstance(val, dict):
            return {k:self.decimalize(v) for k,v in val.items()}

        if isinstance(val, (list, tuple)):
            return type(val)(self.decimalize(v) for v in val)

        if isinstance(val, float):
            return FancyFloat(val)

        return val

    def encode(self, val):
        return super().encode(self.decimalize(val))

JsonRpcEncoder().encode(evil)
#>>> '{"x": 0.00000000000999999999999999939496969281939810930172340963650867706746794283390045166015625}'

,或者,当然,您可以将小数部分移到函数中,并在json.dumps之前调用它.

or, of course, you could move the decimalization out into a function and call that before json.dumps.

即使这是一种me脚的方法,我也是这样做的.

That's how I would do it, even if it's a lame method.

这篇关于在python json.dumps输出中禁用科学计数法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆