From 08b725c7419ef7f3807cd3e42efafd44dc4b5531 Mon Sep 17 00:00:00 2001 From: Hernan Grecco Date: Mon, 1 Jun 2015 00:28:30 -0300 Subject: [PATCH] Added compact formatting code Close #240 --- pint/quantity.py | 9 +++++++-- pint/testsuite/test_quantity.py | 15 +++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/pint/quantity.py b/pint/quantity.py index bd2b7f4..7d20199 100644 --- a/pint/quantity.py +++ b/pint/quantity.py @@ -118,9 +118,14 @@ class _Quantity(SharedRegistryObject): def __format__(self, spec): spec = spec or self.default_format + if '#' in spec: + spec = spec.replace('#', '') + obj = self.to_compact() + else: + obj = self return '{0} {1}'.format( - format(self.magnitude, remove_custom_flags(spec)), - format(self.units, spec)) + format(obj.magnitude, remove_custom_flags(spec)), + format(obj.units, spec)) # IPython related code def _repr_html_(self): diff --git a/pint/testsuite/test_quantity.py b/pint/testsuite/test_quantity.py index ef6954e..d701364 100644 --- a/pint/testsuite/test_quantity.py +++ b/pint/testsuite/test_quantity.py @@ -107,6 +107,21 @@ class TestQuantity(QuantityTestCase): ): self.assertEqual(spec.format(x), result) + def test_format_compact(self): + q1 = (200e-9 * self.ureg.s).to_compact() + q1b = self.Q_(200., 'nanosecond') + self.assertAlmostEqual(q1.magnitude, q1b.magnitude) + self.assertEqual(q1.units, q1b.units) + + q2 = (1e-2 * self.ureg('kg m/s^2')).to_compact('N') + q2b = self.Q_(10., 'millinewton') + self.assertEqual(q2.magnitude, q2b.magnitude) + self.assertEqual(q2.units, q2b.units) + + self.assertEqual('{0:#.1f}'.format(q1), '{0}'.format(q1b)) + self.assertEqual('{0:#.1f}'.format(q2), '{0}'.format(q2b)) + + def test_default_formatting(self): ureg = UnitRegistry() x = ureg.Quantity(4.12345678, UnitsContainer(meter=2, kilogram=1, second=-1))