Handle float values

This commit is contained in:
Jeremy Stretch 2025-03-12 14:27:17 -04:00
parent 486d2bb51b
commit f6ebd0240e
2 changed files with 7 additions and 6 deletions

View File

@ -1,4 +1,4 @@
from decimal import Decimal
from decimal import Decimal, InvalidOperation
from django.utils.translation import gettext as _
@ -42,10 +42,11 @@ def to_meters(length, unit) -> Decimal:
Convert the given length to meters, returning a Decimal value.
"""
try:
length = Decimal(length)
except InvalidOperation:
raise TypeError(_("Invalid value '{length}' for length (must be a number)").format(length=length))
if length < 0:
raise ValueError(_("Length must be a positive number"))
except TypeError:
raise TypeError(_("Invalid value '{length}' for length (must be a number)").format(length=length))
if unit == CableLengthUnitChoices.UNIT_KILOMETER:
return round(Decimal(length * 1000), 4)

View File

@ -28,8 +28,8 @@ class ConversionsTest(TestCase):
def test_to_meters(self):
self.assertEqual(
to_meters(1, CableLengthUnitChoices.UNIT_KILOMETER),
Decimal('1000')
to_meters(1.5, CableLengthUnitChoices.UNIT_KILOMETER),
Decimal('1500')
)
self.assertEqual(
to_meters(1, CableLengthUnitChoices.UNIT_METER),