在python中,怎样才能有一个带两个小数位的float(作为一个float)?

2024-04-20 10:12:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个浮子

x = 2.00

我想把它作为json发送

message = { 'x': 2.00 } 

但当我这么做的时候

print(message)

我看到python去掉了最后一个小数位。我怎样才能把浮点数保持在小数点后两位?我知道2.00和2.0没有什么不同,但我需要发送准确的数字(包括两个小数位)(我尝试过decimal类,它的行为仍然相同,我需要将它作为浮点而不是字符串发送)。提前谢谢。你知道吗


Tags: 字符串jsonmessage数字浮点decimalprint浮点数
3条回答

举个例子:

a=2.00
print ("{0:.2f}".format(a))

您可以定义自己的JSON编码器类:

import json

message = {'x': 2.00}

class MyEncoder(json.JSONEncoder):
    def encode(self, obj):

        if isinstance(obj, dict):
            result = '{'
            for key, value in obj.items():
                if isinstance(value, float):
                    encoded_value = format(value, '.2f')
                else:
                    encoded_value = json.JSONEncoder.encode(self, value)

                result += f'"{key}": {encoded_value}, '

            result = result[:-2] + '}'
            return result
        return json.JSONEncoder.encode(self, obj)

print(json.dumps(message, cls=MyEncoder))

输出:

{"x": 2.00}

您需要使用一个专门的库来序列化浮点并保持精度。protocolbuffers就是这样一个库(Protocol),您可以定义自己的JSON编码器类:https://developers.google.com/protocol-buffers/docs/proto3。你知道吗

相关问题 更多 >