為何 Python 將 JSON 價格解碼為 float 後,Decimal 會顯示額外位數
Why Decimal shows extra digits after Python decodes a JSON price as a float
Python 3.12.16 使用 json.loads 預設將 JSON 價格解碼為二進制浮點數,再轉成 Decimal 時會顯示額外小數位;使用 parse_float=Decimal 則可準確保留 1795.86。
In Python 3.12.16, json.loads with parse_float=Decimal preserved the JSON price 1795.86 exactly.
The price came from prices.values[0] in assets/trade-reviews/EP-0080/case.json. The reconciliation records 1795.86 USDT/ETH as the entry price for a simulated short of 8.071 ETH in the Binance ETHUSDT perpetual contract. The position opened at 14:30 Hong Kong time on November 15, 2026. EP-0080 paper-trade reconciliation
This example decodes the same JSON text twice and reads the price from the same field both times.
import json
from decimal import Decimal
raw = '{"prices":{"values":[1795.86]}}'
direct = json.loads(raw, parse_float=Decimal)["prices"]["values"][0]
via_float = Decimal(json.loads(raw)["prices"]["values"][0])
print(direct)
print(via_float)
print(direct == via_float)
The local Python 3.12.16 run on the original export produced this output.
1795.86
1795.859999999999899955582804977893829345703125
False
With parse_float=Decimal, the JSON decoder passes the original number text to Decimal. The default decoder rounds the price to a representable binary float. Python displays that float as 1795.86 because reading that short spelling back as a float gives the same binary value. Decimal() converts the exact value stored in the float, which is where the extra digits come from.
To check your import for regressions, read the export with data = json.load(export_file, parse_float=Decimal) and assert that data["prices"]["values"][0] == Decimal("1795.86") for this fixture. The local check covered one field. Any effect on orders, fills, or P&L remains unmeasured.
An AI agent drafted this article.
來源:DEV Community · dev.to
