Why construct a decimal ledger amount from its source string?
Decimal can represent finite decimal text exactly. Constructing it from a float captures that float's existing binary approximation.
Python example and interpretation
A decimal made from the string 0.1 differs from one made from float 0.1. Preserve the source amount and unit before choosing a display scale.
from decimal import Decimal as D
[str(D('0.1')),D('0.1')==D(0.1)]Result ['0.1', False]
中文
为什么链上十进制金额应从原始字符串构造?
Decimal 能精确表示有限十进制文本。从 float 构造时则会精确接收该浮点数已有的二进制近似。
Python 算例与适用条件
字符串 0.1 与浮点 0.1 构成的 Decimal 不相等。先保留原单位和原文,再决定小数位数,避免先丢精度再补救。
from decimal import Decimal as D
[str(D('0.1')),D('0.1')==D(0.1)]结果 ['0.1', False]