from decimal import Decimal
'%.2E' % Decimal('40800000000.00000000000000')
# returns '4.08E+10'
In your '40800000000.00000000000000' there are many more significant zeros that have the same meaning as any other digit. That's why you have to tell explicitly where you want to stop.
If you want to remove all trailing zeros automatically, you can try:
def format_e(n):
a = '%E' % n
return a.split('E')[0].rstrip('0').rstrip('.') + 'E' + a.split('E')[1]
format_e(Decimal('40800000000.00000000000000'))
# '4.08E+10'
format_e(Decimal('40000000000.00000000000000'))
# '4E+10'
format_e(Decimal('40812300000.00000000000000'))
# '4.08123E+10'
Answer from eumiro on Stack Overflowfrom decimal import Decimal
'%.2E' % Decimal('40800000000.00000000000000')
# returns '4.08E+10'
In your '40800000000.00000000000000' there are many more significant zeros that have the same meaning as any other digit. That's why you have to tell explicitly where you want to stop.
If you want to remove all trailing zeros automatically, you can try:
def format_e(n):
a = '%E' % n
return a.split('E')[0].rstrip('0').rstrip('.') + 'E' + a.split('E')[1]
format_e(Decimal('40800000000.00000000000000'))
# '4.08E+10'
format_e(Decimal('40000000000.00000000000000'))
# '4E+10'
format_e(Decimal('40812300000.00000000000000'))
# '4.08123E+10'
Here's an example using the format() function:
>>> "{:.2E}".format(Decimal('40800000000.00000000000000'))
'4.08E+10'
Instead of format, you can also use f-strings:
>>> f"{Decimal('40800000000.00000000000000'):.2E}"
'4.08E+10'
official documentation
original format() proposal
Does anyone have a concise cheat sheet for f string formatting with numbers
python - Prevent f string from converting float into scientific notation - Stack Overflow
f strings engineering notation
How to convert scientific notation string to integer?
https://docs.python.org/3.4/library/string.html#format-specification-mini-language
>>> number = 0.0000001
>>> f"Number: {number}"
'Number: 1e-07'
>>> f"Number: {number:f}"
'Number: 0.000000'
>>> f"Number: {number:.10f}"
'Number: 0.0000001000'
By default :f has a precision of 6. You can change it to e.g. 10 with :.10f
After checking other sources, I found numpy.format_float_positional which works very nicely here:
import numpy as np
number = 0.0000001
string = f"Number: {np.format_float_positional(number)}"
Python allows printing a number in scientific notation by: f"a:.2e". But does it allow printing in engineering notation without writing my own print function? I know its a small nitpick but my professor LOVES engineering notation.
For the uninitiated, engineering notation is just scientific notation but the 10 is only to the power of numbers divisible by 3. It makes it easier to tell the scale of a unit. i.e.: 12.345e3 vs 1.2345e4.
Even if there isn't a built-in way to handle this if someone has an elegant solution I would appreciate the help.