python data_error ai_generated true

pydantic.errors.DecimalError: 值不是有效的小数

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

ID: python/pydantic-decimal-precision-loss

其他格式: JSON · Markdown 中文 · English
80%修复率
84%置信度
0证据数
2024-04-18首次发现

版本兼容性

版本状态引入弃用备注
2.x active

根因分析

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

English

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

generic

解决方案

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

无效尝试

常见但无效的做法:

  1. 80% 失败

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

  2. 70% 失败

    If max_digits or decimal_places constraints are set, it fails.