20

How can get following formatting (input values are always less than 0.1):

> formatting(0.09112346)
0.91123E-01
> formatting(0.00112346)
0.11234E-02

and so on.

I am looking for some elegant solution. I am already using a custom function given below:

def formatting(x, prec=5):
    tup    = x.as_tuple()
    digits = list(tup.digits[:prec])
    dec    = ''.join(str(i) for i in digits)
    exp    = x.adjusted()
    return '0.{dec}E{exp}'.format(dec=dec, exp=exp)
ARK4579
  • 663
  • 2
  • 6
  • 16
  • You mean how to get a specific notation when printing a number? – toti08 Nov 13 '18 at 06:52
  • i think yes. (i am not very clear on the concept of "specific notation") – ARK4579 Nov 13 '18 at 06:57
  • Yeah, sorry, I mean printing the number with different notation, like exponential notation, or specifying only a certain amount of digits after the comma, and so on... – toti08 Nov 13 '18 at 07:00

3 Answers3

18

You can use the format() function. The format specification mentions it there:

'E' - Exponent notation. Same as 'e' except it uses an upper case ‘E’ as the separator character.

>>> print('{:.5E}'.format(0.09112346))
9.11235E-02
>>> print('{:.5E}'.format(0.00112346))
1.12346E-03

However it isn't quite like the output you have in your answer. If the above is not satisfactory, then you might use a custom function to help (I'm not the best at this, so hopefully it's ok):

def to_scientific_notation(number):
    a, b = '{:.4E}'.format(number).split('E')
    return '{:.5f}E{:+03d}'.format(float(a)/10, int(b)+1)

print(to_scientific_notation(0.09112346))
# 0.91123E-01
print(to_scientific_notation(0.00112346))
# 0.11234E-02
Jerry
  • 70,495
  • 13
  • 100
  • 144
  • yes, sorry but, that's not the output I am looking for. I am already using a custom function (in my answer) – ARK4579 Nov 13 '18 at 07:37
  • 3
    @ARK4579 Um, sorry, did you read the whole answer? The 2nd part gives the format you asked for (0.91123E-01 and 0.11234E-02) or am I missing something? – Jerry Nov 13 '18 at 07:39
  • 1
    yes, it does. thanks. :) but i am already using a custom function. :) – ARK4579 Nov 13 '18 at 07:53
11

In Python 3.6+, you could also use f-strings. For example:

In [31]: num = 0.09112346

In [32]: f'{num:.5E}'
Out[32]: '9.11235E-02'

It uses the same syntax as str.format(), given in the Format Specification Mini-Language section.


Edit:

The f'{num:.5E}' will always return the number in the normalized scientific notation, meaning that the absolute value of m (=significand) in the returned number [m]E[n] is always between 1 and 10.

If you want to force the absolute value of the significand (m) to be between 0.1 and 1 (0.1 <= |m| < 1.0), then you have to use a custom solution.

Niko Föhr
  • 28,336
  • 10
  • 93
  • 96
0

Another syntax option to format normalized scientific notation:

number = 0.09112346
string = '%.5E' % number
# 9.11235E-02
Wilson
  • 399
  • 2
  • 10