|
173 | 173 |
|
174 | 174 | import six
|
175 | 175 |
|
176 |
| -import decimal |
177 | 176 | import itertools
|
178 | 177 | import locale
|
179 | 178 | import math
|
@@ -1259,40 +1258,38 @@ def format_eng(self, num):
|
1259 | 1258 | u'-1.00 \N{GREEK SMALL LETTER MU}'
|
1260 | 1259 |
|
1261 | 1260 | `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)`. |
1263 | 1262 | """
|
1264 |
| - dnum = decimal.Decimal(str(num)) |
1265 |
| - |
| 1263 | + dnum = float(num) |
1266 | 1264 | sign = 1
|
1267 | 1265 |
|
1268 | 1266 | if dnum < 0:
|
1269 | 1267 | sign = -1
|
1270 | 1268 | dnum = -dnum
|
1271 | 1269 |
|
1272 | 1270 | if dnum != 0:
|
1273 |
| - pow10 = decimal.Decimal(int(math.floor(dnum.log10() / 3) * 3)) |
| 1271 | + pow10 = int(math.floor(math.log10(dnum) / 3) * 3) |
1274 | 1272 | else:
|
1275 |
| - pow10 = decimal.Decimal(0) |
| 1273 | + pow10 = 0 |
1276 | 1274 | # Force dnum to zero, to avoid inconsistencies like
|
1277 | 1275 | # format_eng(-0) = "0" and format_eng(0.0) = "0"
|
1278 | 1276 | # 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 |
1283 | 1278 |
|
1284 |
| - prefix = self.ENG_PREFIXES[int(pow10)] |
| 1279 | + pow10 = np.clip(pow10, min(self.ENG_PREFIXES), max(self.ENG_PREFIXES)) |
1285 | 1280 |
|
1286 | 1281 | 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)] |
1287 | 1290 |
|
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. |
1294 | 1291 | formatted = "{mant:{fmt}}{sep}{prefix}".format(
|
1295 |
| - mant=float(mant), sep=self.sep, prefix=prefix, |
| 1292 | + mant=mant, sep=self.sep, prefix=prefix, |
1296 | 1293 | fmt="g" if self.places is None else ".{:d}f".format(self.places))
|
1297 | 1294 |
|
1298 | 1295 | return formatted
|
|
0 commit comments