Skip to content

Commit 41a69da

Browse files
committed
get rid of decimal.Decimal + fix rounding special cases like 999.9...
1 parent b75f20d commit 41a69da

File tree

1 file changed

+15
-18
lines changed

1 file changed

+15
-18
lines changed

lib/matplotlib/ticker.py

Lines changed: 15 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,6 @@
173173

174174
import six
175175

176-
import decimal
177176
import itertools
178177
import locale
179178
import math
@@ -1259,40 +1258,38 @@ def format_eng(self, num):
12591258
u'-1.00 \N{GREEK SMALL LETTER MU}'
12601259
12611260
`num` may be a numeric value or a string that can be converted
1262-
to a numeric value with the `decimal.Decimal` constructor.
1261+
to a numeric value with `float(num)`.
12631262
"""
1264-
dnum = decimal.Decimal(str(num))
1265-
1263+
dnum = float(num)
12661264
sign = 1
12671265

12681266
if dnum < 0:
12691267
sign = -1
12701268
dnum = -dnum
12711269

12721270
if dnum != 0:
1273-
pow10 = decimal.Decimal(int(math.floor(dnum.log10() / 3) * 3))
1271+
pow10 = int(math.floor(math.log10(dnum) / 3) * 3)
12741272
else:
1275-
pow10 = decimal.Decimal(0)
1273+
pow10 = 0
12761274
# Force dnum to zero, to avoid inconsistencies like
12771275
# format_eng(-0) = "0" and format_eng(0.0) = "0"
12781276
# but format_eng(-0.0) = "-0.0"
1279-
dnum = decimal.Decimal(0)
1280-
1281-
pow10 = pow10.min(max(self.ENG_PREFIXES))
1282-
pow10 = pow10.max(min(self.ENG_PREFIXES))
1277+
dnum = 0.0
12831278

1284-
prefix = self.ENG_PREFIXES[int(pow10)]
1279+
pow10 = np.clip(pow10, min(self.ENG_PREFIXES), max(self.ENG_PREFIXES))
12851280

12861281
mant = sign * dnum / (10 ** pow10)
1282+
# Taking care of the cases like 999.9..., which
1283+
# may be rounded to 1000 instead of 1 k.
1284+
if (self.places is not None and
1285+
round(mant, self.places) >= 1000):
1286+
mant /= 1000
1287+
pow10 += 3
1288+
1289+
prefix = self.ENG_PREFIXES[int(pow10)]
12871290

1288-
# NB: one has to cast *mant* to a float because it is actually
1289-
# an instance of decimal.Decimal. Combined for `str.format`, this
1290-
# may produce strings with more than 6 digits in the case of the
1291-
# "%g" format, which breaks the former behavior that one got with
1292-
# C-style formatting. Another option would be to rely on the
1293-
# `decimal.localcontext()` context manager.
12941291
formatted = "{mant:{fmt}}{sep}{prefix}".format(
1295-
mant=float(mant), sep=self.sep, prefix=prefix,
1292+
mant=mant, sep=self.sep, prefix=prefix,
12961293
fmt="g" if self.places is None else ".{:d}f".format(self.places))
12971294

12981295
return formatted

0 commit comments

Comments
 (0)