Search code examples
pythonformatscientific-notation

Format number to scientific notation, but to 3e-5 instead of 3e-05


I have very small or very big number which I want print in scientific notation:

pattern = "{:.0e}"
value1 = pattern.format(0.00003)
value2 = pattern.format(0.00000000005)
value3 = pattern.format(999999999) 
print(value1, value2, value3)
# Current output: 3e-05 5e-11 1e+09
# Desired output: 3e-5 5e-11 1e+9

Is there any better way to format number into form without 0 after - than value1.replace("-0", "-").replace("+0", "+")? I would like the number to be as short as possible.


Solution

  • Use decimal.

    import decimal
    pattern = "{:.0e}"
    value1 = pattern.format(decimal.Decimal('0.00003'))
    value2 = pattern.format(decimal.Decimal('0.00000000005'))
    value3 = pattern.format(decimal.Decimal('999999999'))
    print(value1, value2, value3)