Skip to content

Commit 9d11d26

Browse files
Implement Value.__format__
1 parent e337aaf commit 9d11d26

2 files changed

Lines changed: 13 additions & 0 deletions

File tree

test/test_value.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -279,3 +279,13 @@ def test_pick_roundtrip() -> None:
279279
x = value * unit
280280
s = pickle.dumps(x)
281281
assert x == pickle.loads(s)
282+
283+
284+
def test_format() -> None:
285+
x = 0.4234324 * tu.ns
286+
assert f'{x:0.2f}' == '0.42 ns'
287+
assert f'{x:e}' == '4.234324e-01 ns'
288+
289+
x = 42.235 * tu.GHz
290+
assert f'{x:0.2f}' == '42.23 GHz'
291+
assert f'{x:0.1e}' == '4.2e+01 GHz'

tunits/core/cython/with_unit.pyx

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -704,6 +704,9 @@ cdef class WithUnit:
704704
self.display_units.__setstate__(pickle_info['display_units'])
705705
self.base_units.__setstate__(pickle_info['base_units'])
706706

707+
def __format__(self, spec: str) -> str:
708+
return self.value.__format__(spec) + ' ' + str(self.unit)
709+
707710
_try_interpret_as_with_unit = None
708711
_is_value_consistent_with_default_unit_database = None
709712
def init_base_unit_functions(

0 commit comments

Comments
 (0)