Skip to content

Commit c98ba91

Browse files
committed
more complete handling of corner-case roundings + add proper tests
1 parent 0bde03a commit c98ba91

File tree

2 files changed

+11
-7
lines changed

2 files changed

+11
-7
lines changed

lib/matplotlib/tests/test_ticker.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -564,11 +564,13 @@ class TestEngFormatter(object):
564564
(0.1, ('100 m', '100 m', '100.00 m')),
565565
(1, ('1', '1', '1.00')),
566566
(1.23456789, ('1.23457', '1', '1.23')),
567-
(999.9, ('999.9', '1 k', '999.90')),
567+
(999.9, ('999.9', '1 k', '999.90')), # places=0: corner-case rounding
568+
(999.9999, ('1 k', '1 k', '1.00 k')), # corner-case roudning for all
568569
(1000, ('1 k', '1 k', '1.00 k')),
569570
(1001, ('1.001 k', '1 k', '1.00 k')),
570571
(100001, ('100.001 k', '100 k', '100.00 k')),
571-
(987654.321, ('987.654 k', '988 k', '987.65 k'))
572+
(987654.321, ('987.654 k', '988 k', '987.65 k')),
573+
(1.23e27, ('1230 Y', '1230 Y', '1230.00 Y')) # OoR value (> 1000 Y)
572574
]
573575

574576
@pytest.mark.parametrize('input, expected', raw_format_data)

lib/matplotlib/ticker.py

+7-5
Original file line numberDiff line numberDiff line change
@@ -1265,6 +1265,7 @@ def format_eng(self, num):
12651265
"""
12661266
dnum = float(num)
12671267
sign = 1
1268+
fmt = "g" if self.places is None else ".{:d}f".format(self.places)
12681269

12691270
if dnum < 0:
12701271
sign = -1
@@ -1283,17 +1284,18 @@ def format_eng(self, num):
12831284

12841285
mant = sign * dnum / (10.0 ** pow10)
12851286
# Taking care of the cases like 999.9..., which
1286-
# may be rounded to 1000 instead of 1 k.
1287-
if (self.places is not None and
1288-
round(mant, self.places) >= 1000):
1287+
# may be rounded to 1000 instead of 1 k. Beware
1288+
# of the corner case of values that are beyond
1289+
# the range of SI prefixes (i.e. > 'Y').
1290+
_fmant = float("{mant:{fmt}}".format(mant=mant, fmt=fmt))
1291+
if _fmant >= 1000 and pow10 != max(self.ENG_PREFIXES):
12891292
mant /= 1000
12901293
pow10 += 3
12911294

12921295
prefix = self.ENG_PREFIXES[int(pow10)]
12931296

12941297
formatted = "{mant:{fmt}}{sep}{prefix}".format(
1295-
mant=mant, sep=self.sep, prefix=prefix,
1296-
fmt="g" if self.places is None else ".{:d}f".format(self.places))
1298+
mant=mant, sep=self.sep, prefix=prefix, fmt=fmt)
12971299

12981300
return formatted
12991301

0 commit comments

Comments
 (0)