python
data_error
ai_generated
true
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%Fix Rate
87%Confidence
0Evidence
2024-09-05First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 2.x | active | — | — | — |
Root Cause
A Decimal field declared with max_digits/decimal_places received a value with more fractional digits than allowed.
generic中文
声明了 max_digits/decimal_places 的 Decimal 字段接收到了小数位数超过限制的值。
Workarounds
-
92% success
from decimal import Decimal, ROUND_HALF_UP v = Decimal('1.2345').quantize(Decimal('0.01'), rounding=ROUND_HALF_UP) Price(value=v) -
90% success
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)
Dead Ends
Common approaches that don't work:
-
60% fail
Introduces binary floating-point rounding; 1.2345 becomes 1.2344999...
-
50% fail
Defeats the purpose and allows inconsistent money precision downstream.
-
70% fail
Silently zeroes real prices, causing financial data corruption.