Unit testing
When developing a utility function like this it's good to create unit tests so you can refactor safely, knowing when you break something. Let's say your code above is in a file called prettyprint.py
, you could create a file with unit tests in prettyprint_tests.py
like this:
import unittest
from test.test_support import run_unittest
from prettyprint import eng_format
class FormatTestCase(unittest.TestCase):
def test_examples(self):
self.assertEquals('2.00mV', eng_format(0.002, 'V'))
self.assertEquals('3.22uA', eng_format(0.000003221, 'A'))
self.assertEquals('30.59kA', eng_format(30589, 'A'))
self.assertEquals('60.00MW', eng_format(60000000, 'W'))
self.assertEquals('6.00*10^15 W', eng_format(6000000000000000, 'W'))
self.assertEquals('600.00*10^-18 W', eng_format(.0000000000000006, 'W'))
if __name__ == '__main__':
run_unittest(FormatTestCase)
Coding style
PEP8 is the official style guide for Python. It's good to follow it, it makes your code more readable by everyone following the standard.
Even more importantly, it would be better to use more meaningful variable names, and to remove unnecessary brackets, for example:
def eng_format(x, unit):
magnitude = math.floor(math.log10(x)) // 3 * 3
suffixes = ['f', 'p', 'n', 'u', 'm', '', 'k', 'M', 'G']
idx = int(magnitude / 3) + suffixes.index('')
if idx < 0 or idx >= len(suffixes):
suffix = '*10^%d ' % magnitude
else:
suffix = suffixes[idx]
nx = x / 10 ** magnitude
return '%.2f%s%s' % (nx, suffix, unit)
Other than these minor issues, your code seems fine to me.
str.format
e.g.'*10^{0} '.format(e)
rather than'*10^%d '%e
\$\endgroup\$