Convert Floats to Engineering Notation

A useful utility in the engineer’s software toolbox is to be able to convert a floating point number to engineering format (that is, with an exponent which is a multiple of 3).  You should be able to specify number of significant digits, and possibly a letter suffix for kilo, mega, micro, etc.  In other words, you’d like to convert 1.2345e2 to 123.5, or 1e-7 to 100n, or 6.4983e4 to 65.5k.  It’s also nice to be able to suppress negative values, when the result is to be a real component (for example).

It’s actually pretty tricky to do this and have it work right for the whole range of positive and negative numbers and arbitrary exponents.  I found some solutions which were almost correct, but 1e-6 would be converted to 1000n instead of 1u while 1e6 converted correctly to 1M, and so forth.

Here’s a Python 3 function for this type of conversion.  You provide eng_notate() with a floating point number, and it returns a string.  You can specify the number of significant digits, whether to use letter suffixes or exponential notation, and whether negative numbers are allowed.

Here is the output of a test run using the default settings (three significant digits, suffixes used, and negative numbers not allowed):

You can see where “RangeErr” is returned for negative numbers, and numbers beyond the range of the _SUFFIX list are expressed with < or > indicators.  In between, the floats are converted to convenient engineering notation.