Question

I am trying to print exponential number in python but I need my number to start by dot. Something like :

>>>print( "{:+???}".format(1.2345678) )
+.1234e+01
Was it helpful?

Solution

If you multiply your number by 10 and format the number with scientific notation, you will have the correct exponent but the coma will be misplaced. Fortunately, you know that there is exactly one character for the sign and exactly one digit before the coma. So you can do

def format_exponential_with_leading_dot(n):
    a = "{:+e}".format(n * 10)
    return a[0] + '.' + a[1] + a[3:]


>>> print format_exponential_with_leading_dot(1.2345678)
+.1234568e+01

OTHER TIPS

Here is an incredibly disgusting way to do it:

import numpy as np
num = 1.2345678
print str(num/10**(int(np.log10(num))+1)).lstrip('0')+'e{0}'.format(str((int(np.log10(num))+1)).zfill(2))

>>>.123456768e01

Here is a better way (I think):

import re
num = 1.2345678
m_ = re.search('([0-9]*)[.]([0-9]*)', str(num))
print('.{0}e+{1}'.format(m_.group(1)+m_.group(2), str(len(m_.group(1))).zfill(2)))

>>>.123456768e+01

If you convert either output string with:

float(output_string)

you get your original number.

Works with negative numbers and can use negative exponents

import math
num = -0.002342
print '{}.{}e{}{}'.format('+' if num >= 0 else '-', str(abs(num)).replace('.','').lstrip('0'), '+' if abs(num) >= 1 else '-', str(abs(int(math.log10(abs(num)) + (1 if abs(num) > 1 else 0)))).zfill(2))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top