python
data_error
ai_generated
true
pydantic_core._pydantic_core.ValidationError:1 个验证错误(Price) value Decimal 输入的小数位数不应超过 2 位 [type=decimal_max_places, input_value='1.2345', input_type=str]
pydantic_core._pydantic_core.ValidationError: 1 validation error for Price value Decimal input should have no more than 2 decimal places [type=decimal_max_places, input_value='1.2345', input_type=str]
ID: python/pydantic-decimal-max-digits
80%修复率
87%置信度
0证据数
2024-09-05首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 2.x | active | — | — | — |
根因分析
声明了 max_digits/decimal_places 的 Decimal 字段接收到了小数位数超过限制的值。
English
A Decimal field declared with max_digits/decimal_places received a value with more fractional digits than allowed.
解决方案
-
92% 成功率
from decimal import Decimal, ROUND_HALF_UP v = Decimal('1.2345').quantize(Decimal('0.01'), rounding=ROUND_HALF_UP) Price(value=v) -
90% 成功率
from pydantic import BaseModel, field_validator, Field from decimal import Decimal, ROUND_HALF_UP class Price(BaseModel): value: Decimal = Field(max_digits=10, decimal_places=2) @field_validator('value', mode='before') @classmethod def quantize(cls, v): return Decimal(str(v)).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
无效尝试
常见但无效的做法:
-
60% 失败
Introduces binary floating-point rounding; 1.2345 becomes 1.2344999...
-
50% 失败
Defeats the purpose and allows inconsistent money precision downstream.
-
70% 失败
Silently zeroes real prices, causing financial data corruption.