mirror of
https://github.com/pretix/pretix.git
synced 2026-05-10 16:04:02 +00:00
Fix normalization
This commit is contained in:
@@ -20,6 +20,7 @@
|
||||
# <https://www.gnu.org/licenses/>.
|
||||
#
|
||||
import copy
|
||||
from decimal import Decimal
|
||||
|
||||
from django.core.files import File
|
||||
from django.db import models
|
||||
@@ -57,6 +58,21 @@ def flatten_choices(choices):
|
||||
yield value_or_group, label_or_nested
|
||||
|
||||
|
||||
def _normalize_decimal(d: Decimal) -> Decimal:
|
||||
"""
|
||||
Strips trailing zeros, e.g.
|
||||
|
||||
20.000 → 20
|
||||
20.010 → 20.01
|
||||
20.100 → 20.1
|
||||
|
||||
But unlike of Decimal.normalize(), 20.000 will not become 2e+1
|
||||
"""
|
||||
normalized = d.normalize()
|
||||
sign, digit, exponent = normalized.as_tuple()
|
||||
return normalized if exponent <= 0 else normalized.quantize(1)
|
||||
|
||||
|
||||
class NormalizedDecimalField(DecimalField):
|
||||
"""
|
||||
Variant of DecimalField that never outputs the trailing zeros, so we always have normalized decimals internally.
|
||||
@@ -65,5 +81,5 @@ class NormalizedDecimalField(DecimalField):
|
||||
|
||||
def from_db_value(self, value, expression, connection):
|
||||
if value is not None:
|
||||
value = value.normalize()
|
||||
value = _normalize_decimal(value)
|
||||
return value
|
||||
|
||||
Reference in New Issue
Block a user