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

其他格式: JSON · Markdown 中文 · English
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.

generic

解决方案

  1. 92% 成功率
    from decimal import Decimal, ROUND_HALF_UP
    v = Decimal('1.2345').quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
    Price(value=v)
  2. 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)

无效尝试

常见但无效的做法:

  1. 60% 失败

    Introduces binary floating-point rounding; 1.2345 becomes 1.2344999...

  2. 50% 失败

    Defeats the purpose and allows inconsistent money precision downstream.

  3. 70% 失败

    Silently zeroes real prices, causing financial data corruption.