diff --git a/core/src/trezor/utils.py b/core/src/trezor/utils.py index 070c5b994..7e96389ba 100644 --- a/core/src/trezor/utils.py +++ b/core/src/trezor/utils.py @@ -74,8 +74,13 @@ def chunks(items: List[Chunked], size: int) -> Iterator[List[Chunked]]: def format_amount(amount: int, decimals: int) -> str: + if amount < 0: + amount = -amount + sign = "-" + else: + sign = "" d = pow(10, decimals) - s = ("%d.%0*d" % (amount // d, decimals, amount % d)).rstrip("0").rstrip(".") + s = ("%s%d.%0*d" % (sign, amount // d, decimals, amount % d)).rstrip("0").rstrip(".") return s diff --git a/core/tests/test_trezor.utils.py b/core/tests/test_trezor.utils.py index 0adba98f4..c62635a7b 100644 --- a/core/tests/test_trezor.utils.py +++ b/core/tests/test_trezor.utils.py @@ -13,6 +13,16 @@ class TestUtils(unittest.TestCase): self.assertEqual(c[i].stop, 100 if (i == 14) else (i + 1) * 7) self.assertEqual(c[i].step, 1) + def test_format_amount(self): + VECTORS = [ + (123456, 3, "123.456"), + (4242, 7, "0.0004242"), + (-123456, 3, "-123.456"), + (-4242, 7, "-0.0004242"), + ] + for v in VECTORS: + self.assertEqual(utils.format_amount(v[0], v[1]), v[2]) + if __name__ == '__main__': unittest.main()