How to make exponential number print with leading point in python?

I am trying to print an exponential number in python, but I need my number to start with a dot. Sort of:

>>>print( "{:+???}".format(1.2345678) )
+.1234e+01
+4
source share
3 answers

If you multiply your number by 10 and format the number with scientific notation, you will have the correct indicator, but the coma will be inappropriate. Fortunately, you know that in front of a sign there is exactly one symbol for the sign and exactly one digit. 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
+1
source

Here's an incredibly disgusting way to do this:

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 the best 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 the output string with:

float(output_string)

You will receive your original number.

+1

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))
0

Source: https://habr.com/ru/post/1525580/


All Articles