Skip to main content
 首页 » 编程设计

python之为什么我必须求助于字符串来获得准确的数字处理

2025年05月04日12qq78292959

将数据转换为十进制时,有时我仍然会得到不正确的结果:

from decimal import * 
D = Decimal 
>>> D(5.2).quantize(D('.00000'), rounding=ROUND_DOWN) 
Decimal('5.20000') 
>>> D(5.3).quantize(D('.00000'), rounding=ROUND_DOWN) 
Decimal('5.29999') 

我不认为浮点不精确是这里的借口,因为我正在使用专门的类来处理数字! 引自 pyton 文档:

Decimal “is based on a floating-point model which was designed with people in mind, and necessarily has a paramount guiding principle – computers must provide an arithmetic that works in the same way as the arithmetic that people learn at school.” – excerpt from the decimal arithmetic specification

这个有效:

x=round(x - .0000049,5) 
D(str(x) + (5-len(str(x).split('.')[1]))*'0') 

请您参考如下方法:

因为5.3 本身已经是错误的。当您将它传递给 Decimal() 时,它不会神奇地修复它。从一开始,您就需要在每一步都使用 Decimal()。这意味着编写 Decimal('5.3') 而不是 Decimal(5.3)。

编辑:OP 声明他们正在使用 JSON。以下是从 JSON 解析 Decimals 的方法:

import json, decimal 
decimal_decoder = json.JSONDecoder(parse_float=decimal.Decimal) 
parsed_json = decimal_decoder.decode(raw_json) 

(其中 raw_json 是作为字符串的 JSON)。这将产生正确的小数。