Skip to content

Commit

Permalink
resolved issue: Inconsistent sig figs with values <1 #5. github.com//…
Browse files Browse the repository at this point in the history
  • Loading branch information
BebeSparkelSparkel committed Jan 19, 2018
1 parent d2e9a7e commit bfe6807
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 10 deletions.
10 changes: 10 additions & 0 deletions tests.py → test.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,11 @@ def test_multi(self):
# sig zero
self.assertEqual(std_notation(10, 2), '10.')

def test_values_less_than_1(self):
# github.com/BebeSparkelSparkel/to-precision/issues/5
self.assertEqual(std_notation(0.999999, 3), '1.00')
self.assertEqual(std_notation(-0.999999, 3), '-1.00')

class TestSciNotation(unittest.TestCase):
def test_multi(self):
self.assertEqual(sci_notation(1, 1), '1e0')
Expand All @@ -193,6 +198,11 @@ def test_multi(self):
self.assertEqual(sci_notation(123, 3), '1.23e2')
self.assertEqual(sci_notation(-123, 4), '-1.230e2') # round down

def test_values_less_than_1(self):
# github.com/BebeSparkelSparkel/to-precision/issues/5
self.assertEqual(sci_notation(0.999999, 3), '1.00e0')
self.assertEqual(sci_notation(-0.999999, 3), '-1.00e0')

class TestPlaceDot(unittest.TestCase):
def test_all(self):
self.assertEqual(_place_dot('123', 0, False), '123')
Expand Down
31 changes: 21 additions & 10 deletions to_precision.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
__author__ = '''William Rusnack github.com/BebeSparkelSparkel linkedin.com/in/williamrusnack williamrusnack@gmail.com
Eric Moyer github.com/epmoyer eric@lemoncrab.com'''
__author__ = '''
William Rusnack github.com/BebeSparkelSparkel linkedin.com/in/williamrusnack williamrusnack@gmail.com
Eric Moyer github.com/epmoyer eric@lemoncrab.com
Thomas Hladish https://github.com/tjhladish tjhladish@utexas.edu
'''

from math import floor, log10

Expand Down Expand Up @@ -263,22 +266,30 @@ def _number_profile(value, precision):
github.com/BebeSparkelSparkel
linkedin.com/in/williamrusnack/
williamrusnack@gmail.com
contributions by Thomas Hladish
github.com/tjhladish
Issue: github.com/BebeSparkelSparkel/to-precision/issues/5
'''
value = float(value)
is_neg = value < 0
value = abs(value)

if value == 0:
sig_digits = '0' * precision
power = -(1 - precision)
is_neg = False

else:
if value < 0:
value = abs(value)
is_neg = True
else:
is_neg = False

power = -1 * floor(log10(value)) + precision - 1
sig_digits = str(int(round(abs(value) * 10.0**power)))

# issue soved by Thomas Haladish
# github.com/BebeSparkelSparkel/to-precision/issues/5
value_power = value * 10.0**power
if value < 1 and \
floor(log10(int(round(value_power)))) > \
floor(log10(int(value_power))):
power -= 1

sig_digits = str(int(round(value * 10.0**power)))

return sig_digits, int(-power), is_neg

0 comments on commit bfe6807

Please sign in to comment.