Skip to content

Commit 912e334

Browse files
committed
Math: Round trailing nines up in @convert
1 parent 56e06a9 commit 912e334

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

plugins/Math/plugin.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,7 @@ def convert(self, irc, msg, args, number, unit1, unit2):
253253
digits = len(str(number).split('.')[1])
254254
except IndexError:
255255
digits = 0
256+
256257
try:
257258
newNum = convertcore.convert(number, unit1, unit2)
258259
if isinstance(newNum, float):
@@ -261,11 +262,23 @@ def convert(self, irc, msg, args, number, unit1, unit2):
261262
if char != '0':
262263
break
263264
zeros += 1
265+
264266
# Let's add one signifiant digit. Physicists would not like
265267
# that, but common people usually do not give extra zeros...
266268
# (for example, with '32 C to F', an extra digit would be
267269
# expected).
268270
newNum = round(newNum, digits + 1 + zeros)
271+
272+
# However, if the difference is negligeable compared to the
273+
# precision we got in the input, we remove two more digits.
274+
# this is useful for rounding .9999999 up.
275+
newNum2 = round(newNum, digits - 1 + zeros)
276+
try:
277+
if abs((newNum2 - newNum) / newNum) < 10**(-digits-10):
278+
newNum = newNum2
279+
except ZeroDivisionError:
280+
pass
281+
269282
newNum = self._floatToString(newNum)
270283
irc.reply(str(newNum))
271284
except convertcore.UnitDataError as ude:

plugins/Math/test.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,13 @@ def testConvert(self):
188188
self.assertError('convert 1 mol to grams')
189189
self.assertError('convert 1 m to kpa')
190190

191+
def testConvertSignificantDigits(self):
192+
self.assertResponse('convert 1 s to ns', '1000000000')
193+
self.assertResponse('convert 0.9999999999999999 s to ns',
194+
'999999999.9999999')
195+
self.assertResponse('convert 1000000000 ns to s', '1')
196+
self.assertResponse('convert 999999999.9999999 ns to s', '1')
197+
191198
def testConvertSingularPlural(self):
192199
self.assertResponse('convert [calc 2*pi] rads to degrees', '360')
193200
self.assertResponse('convert 1 carat to grams', '0.2')

0 commit comments

Comments
 (0)