I am trying to print a number into engineering format with python, but I cannot seem to get it to work. The syntax SEEMS simple enough, but it just doesn’t work.
>>> import decimal
>>> x = decimal.Decimal(1000000)
>>> print x
1000000
>>>> print x.to_eng_string()
1000000
I cannot figure out why this is. The two values are not equal (one is a string, the other is an int). Setting various contexts in decimal doesn’t seem to help either. Any clues or ideas?
To get this to work, you have to normalize the decimal first:
The reason for this can be discovered by delving in to the source code.
If you examine
to_eng_string()in the Python 2.7.3 source tree (Lib/decimal.pyfrom the gzipped source tar ball here), it simply calls__str__withengset to true.You can then see that it decides on how many digits go to the left of the decimal initially with:
The following table shows what the values are for those two things:
The code that continues after that is:
and you can see that, unless it already has an exponent in a certain range (
self._exp > 0 or leftdigits <= -6), none will be given to it in the string representation.Further investigation shows the reason for this behaviour. Looking at the code itself, you’ll see it’s based on the
General Decimal Arithmetic Specification(PDF here).If you search that document for
to-scientific-string(on whichto-engineering-stringis heavily based), it states in part (paraphrased, and with my bold bits):In other words, it’s doing what it’s doing because that’s what the standard tells it to do.