Skip to content

Commit

Permalink
Fix Decimal trailing zero handling (#5962)
Browse files Browse the repository at this point in the history
  • Loading branch information
hramezani committed Jun 1, 2023
1 parent e4362c9 commit 86cd20b
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
6 changes: 5 additions & 1 deletion pydantic/_internal/_std_types_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,11 @@ def validate(self, __input_value: int | float | str) -> decimal.Decimal: # noqa
raise PydanticCustomError('decimal_parsing', 'Input should be a valid decimal')

if not self.allow_inf_nan or self.check_digits:
_1, digit_tuple, exponent = value.as_tuple()
try:
normalized_value = value.normalize()
except decimal.InvalidOperation:
normalized_value = value
_1, digit_tuple, exponent = normalized_value.as_tuple()
if not self.allow_inf_nan and exponent in {'F', 'n', 'N'}:
raise PydanticKnownError('finite_number')

Expand Down
22 changes: 18 additions & 4 deletions tests/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -2963,6 +2963,20 @@ class Model(BaseModel):
(dict(max_digits=4, decimal_places=1), Decimal('999'), Decimal('999')),
(dict(max_digits=20, decimal_places=2), Decimal('742403889818000000'), Decimal('742403889818000000')),
(dict(max_digits=20, decimal_places=2), Decimal('7.42403889818E+17'), Decimal('7.42403889818E+17')),
(dict(max_digits=6, decimal_places=2), Decimal('000000000001111.700000'), Decimal('000000000001111.700000')),
(
dict(max_digits=6, decimal_places=2),
Decimal('0000000000011111.700000'),
[
{
'type': 'decimal_whole_digits',
'loc': ('foo',),
'msg': 'ensure that there are no more than 4 digits before the decimal point',
'input': Decimal('11111.700000'),
'ctx': {'whole_digits': 4},
}
],
),
(
dict(max_digits=20, decimal_places=2),
Decimal('7424742403889818000000'),
Expand Down Expand Up @@ -2994,15 +3008,15 @@ class Model(BaseModel):
),
(dict(max_digits=5, decimal_places=5), Decimal('70E-5'), Decimal('70E-5')),
(
dict(max_digits=5, decimal_places=5),
dict(max_digits=4, decimal_places=4),
Decimal('70E-6'),
[
{
'loc': ('foo',),
'msg': 'ensure that there are no more than 5 digits in total',
'msg': 'ensure that there are no more than 4 digits in total',
'type': 'decimal_max_digits',
'input': Decimal('0.000070'),
'ctx': {'max_digits': 5},
'input': Decimal('0.00007'),
'ctx': {'max_digits': 4},
}
],
),
Expand Down

0 comments on commit 86cd20b

Please sign in to comment.