python data_error ai_generated true

pydantic.errors.DecimalError: value is not a valid decimal

ID: python/pydantic-decimal-precision-loss

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2024-04-18First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.x active

Root Cause

When using Decimal type, input is a float or string that cannot be precisely converted to Decimal, causing precision loss or invalid format.

generic

中文

使用 Decimal 类型时,输入是浮点数或无法精确转换为 Decimal 的字符串,导致精度丢失或格式无效。

Workarounds

  1. 90% success
    Pass string representation: Decimal('123.45')
  2. 85% success
    Use condecimal with proper constraints: price: condecimal(max_digits=10, decimal_places=2)

Dead Ends

Common approaches that don't work:

  1. 80% fail

    Float has binary representation issues; Pydantic may raise DecimalError or lose precision.

  2. 70% fail

    If max_digits or decimal_places constraints are set, it fails.