Skip to content

Commit

Permalink
Math: Round trailing nines up in @convert
Browse files Browse the repository at this point in the history
  • Loading branch information
progval committed Dec 19, 2024
1 parent 56e06a9 commit 912e334
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
13 changes: 13 additions & 0 deletions plugins/Math/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,7 @@ def convert(self, irc, msg, args, number, unit1, unit2):
digits = len(str(number).split('.')[1])
except IndexError:
digits = 0

try:
newNum = convertcore.convert(number, unit1, unit2)
if isinstance(newNum, float):
Expand All @@ -261,11 +262,23 @@ def convert(self, irc, msg, args, number, unit1, unit2):
if char != '0':
break
zeros += 1

# Let's add one signifiant digit. Physicists would not like
# that, but common people usually do not give extra zeros...
# (for example, with '32 C to F', an extra digit would be
# expected).
newNum = round(newNum, digits + 1 + zeros)

# However, if the difference is negligeable compared to the
# precision we got in the input, we remove two more digits.
# this is useful for rounding .9999999 up.
newNum2 = round(newNum, digits - 1 + zeros)
try:
if abs((newNum2 - newNum) / newNum) < 10**(-digits-10):
newNum = newNum2
except ZeroDivisionError:
pass

newNum = self._floatToString(newNum)
irc.reply(str(newNum))
except convertcore.UnitDataError as ude:
Expand Down
7 changes: 7 additions & 0 deletions plugins/Math/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,13 @@ def testConvert(self):
self.assertError('convert 1 mol to grams')
self.assertError('convert 1 m to kpa')

def testConvertSignificantDigits(self):
self.assertResponse('convert 1 s to ns', '1000000000')
self.assertResponse('convert 0.9999999999999999 s to ns',
'999999999.9999999')
self.assertResponse('convert 1000000000 ns to s', '1')
self.assertResponse('convert 999999999.9999999 ns to s', '1')

def testConvertSingularPlural(self):
self.assertResponse('convert [calc 2*pi] rads to degrees', '360')
self.assertResponse('convert 1 carat to grams', '0.2')
Expand Down

0 comments on commit 912e334

Please sign in to comment.