diff --git a/ph_units/unit_type.py b/ph_units/unit_type.py index 5f2fea7..e99026a 100644 --- a/ph_units/unit_type.py +++ b/ph_units/unit_type.py @@ -71,12 +71,12 @@ def unit(self): def as_a(self, unit): # type: (str) -> Unit - """Return a new Unit in the specified unit-type.""" - new_value = convert(self.value, self.unit, unit) - if not new_value: - raise ValueError( - "Cannot convert from '{}' to '{}'.".format(self.unit, unit) - ) + """Return a new Unit with the value converted to the specified unit-type.""" + try: + new_value = convert(self.value, self.unit, unit) + except Exception as e: + msg = "Error trying to convert '{}' from '{}' to '{}'".format(self.value, self.unit, unit) + raise ValueError(msg, e) return Unit(new_value, unit) def _invert_unit(self, unit): diff --git a/tests/test_as_a.py b/tests/test_as_a.py new file mode 100644 index 0000000..a9a6869 --- /dev/null +++ b/tests/test_as_a.py @@ -0,0 +1,8 @@ +from ph_units.unit_type import Unit + +def test_basic_use() -> None: + assert Unit(1.0, "KWH").as_a("KBTU") == Unit(3.41214, "KBTU") + + +def test_zero_value() -> None: + assert Unit(0, "KWH").as_a("KBTU") == Unit(0, "KBTU")