Skip to content

Commit 179bf32

Browse files
committed
Fix Quantity.to_string() for non-latex format, fixes #11131
1 parent eb49d2d commit 179bf32

3 files changed

Lines changed: 15 additions & 2 deletions

File tree

‎CHANGES.rst‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1175,6 +1175,9 @@ astropy.units
11751175
- Ensure ``keepdims`` works for taking ``mean``, ``std``, and ``var`` of
11761176
``Quantity``. [#11198]
11771177

1178+
- For ``Quantity.to_string()``, ensure that the precision argument is also
1179+
used when the format is not latex. [#11145]
1180+
11781181
astropy.utils
11791182
^^^^^^^^^^^^^
11801183

‎astropy/units/quantity.py‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1169,14 +1169,20 @@ def to_string(self, unit=None, precision=None, format=None, subfmt=None):
11691169
if format not in formats:
11701170
raise ValueError(f"Unknown format '{format}'")
11711171
elif format is None:
1172-
return f'{self.value}{self._unitstr:s}'
1172+
if precision is None:
1173+
# Use default formatting settings
1174+
return f'{self.value}{self._unitstr:s}'
1175+
else:
1176+
# np.array2string properly formats arrays as well as scalars
1177+
return np.array2string(self.value, precision=precision, floatmode="fixed") + self._unitstr
11731178

11741179
# else, for the moment we assume format="latex"
11751180

11761181
# need to do try/finally because "threshold" cannot be overridden
11771182
# with array2string
1178-
pops = np.get_printoptions()
11791183

1184+
# Set the precision if set, otherwise use numpy default
1185+
pops = np.get_printoptions()
11801186
format_spec = f".{precision if precision is not None else pops['precision']}g"
11811187

11821188
def float_formatter(value):

‎astropy/units/tests/test_quantity.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -913,6 +913,10 @@ def test_to_string(self):
913913
res = 'Quantity as KMS: 150000000000.0 km / s'
914914
assert f"Quantity as KMS: {qscalar.to_string(unit=u.km / u.s)}" == res
915915

916+
# With precision set
917+
res = 'Quantity as KMS: 1.500e+11 km / s'
918+
assert f"Quantity as KMS: {qscalar.to_string(precision=3, unit=u.km / u.s)}" == res
919+
916920
res = r'$1.5 \times 10^{14} \; \mathrm{\frac{m}{s}}$'
917921
assert qscalar.to_string(format="latex") == res
918922

0 commit comments

Comments
 (0)