diff --git a/CHANGES b/CHANGES index 588e7f5b7..52bdf1a8a 100644 --- a/CHANGES +++ b/CHANGES @@ -6,6 +6,7 @@ Pint Changelog - Fix custom formatter needing the registry object. (PR #2011) - Support python 3.9 following difficulties installing with NumPy 2. (PR #2019) +- Fix default formatting of dimensionless unit issue. (PR #2012) 0.24 (2024-06-07) ----------------- diff --git a/pint/delegates/formatter/_compound_unit_helpers.py b/pint/delegates/formatter/_compound_unit_helpers.py index 7631a94ef..5757b46fa 100644 --- a/pint/delegates/formatter/_compound_unit_helpers.py +++ b/pint/delegates/formatter/_compound_unit_helpers.py @@ -256,6 +256,12 @@ def prepare_compount_unit( # out: unit_name, unit_exponent + if len(out) == 0: + if "~" in spec: + return ([], []) + else: + return ([("dimensionless", 1)], []) + if "~" in spec: if registry is None: raise ValueError( diff --git a/pint/delegates/formatter/_format_helpers.py b/pint/delegates/formatter/_format_helpers.py index 995159e65..8a2f37a59 100644 --- a/pint/delegates/formatter/_format_helpers.py +++ b/pint/delegates/formatter/_format_helpers.py @@ -131,6 +131,8 @@ def join_mu(joint_fstring: str, mstr: str, ustr: str) -> str: This avoids that `3 and `1 / m` becomes `3 1 / m` """ + if ustr == "": + return mstr if ustr.startswith("1 / "): return joint_fstring.format(mstr, ustr[2:]) return joint_fstring.format(mstr, ustr) diff --git a/pint/testsuite/test_issues.py b/pint/testsuite/test_issues.py index 44caafbca..ead3672e0 100644 --- a/pint/testsuite/test_issues.py +++ b/pint/testsuite/test_issues.py @@ -1285,3 +1285,21 @@ def _test_format(unit, registry, **options): base_unit = ureg.microsecond assert f"{base_unit:~test}" == "us" assert f"{base_unit:test}" == "microsecond" + + +def test_issue2007(): + ureg = UnitRegistry() + q = ureg.Quantity(1, "") + assert f"{q:P}" == "1 dimensionless" + assert f"{q:C}" == "1 dimensionless" + assert f"{q:D}" == "1 dimensionless" + assert f"{q:H}" == "1 dimensionless" + + assert f"{q:L}" == "1\\ \\mathrm{dimensionless}" + # L returned '1\\ dimensionless' in pint 0.23 + + assert f"{q:Lx}" == "\\SI[]{1}{}" + assert f"{q:~P}" == "1" + assert f"{q:~C}" == "1" + assert f"{q:~D}" == "1" + assert f"{q:~H}" == "1"