Scientific notation with more than 1 digit to the point

Is there any way in python to make a string from a number that runs like this:

  • raw number: 30.0123456789

    • result: 30.0123
  • raw number: 0.0123456789

    • result: 12.3457e-3
  • raw number: 0.000123456789

    • result: 12.3457e-5
  • raw number: 12345.67891011

    • result: 12.3457e3

In this case, it will always be 4 decimal places after the decimal point (filled with zeros, if applicable)

It would always be 2 numbers to a decimal point

+4
source share
3 answers

You can write your own format function based on scientific notation.

def format(num,kk,cc=12):
    # kk - digits before dot , cc - digits after dot
    fmt = '{0:.'+str(kk+cc-1)+'e}'
    ss = fmt.format(num);
    s1 = ss.replace('.','')
    p1 = s1.split('e')
    a1 = p1[0]
    a2 = int(p1[1])
    return '{0}.{1}e{2}'.format(a1[0:kk],a1[kk:],a2-kk+1) 

For convenience, you can create an object with a custom format:

class MyNum:
    def __init__(self,value):
        self.value = value
    def __format__(self,fmt):
        args = fmt.split('.')
        a1 = int(args[0]) if len(args) > 0 else 1
        a2 = int(args[1]) if len(args) > 1 else 6
        return format(self.value,a1,a2)

:

print('{0:3.6}'.format(MyNum(25.123456789)))
#print 251.234568e-1
+2

math.log10 , , -, ( ):

from math import log10, ceil
numbers = [30.0123456789, 0.0123456789, 0.000123456789, 12345.67891011]

n = 2
for number in numbers:
    e = ceil(log10(number) - n)
    n_digits = number * 10**-e
    if e:
        print('%.4fe%d' % (n_digits, e))
    else:
        print('%.4f' % number)

#   30.0123
#   12.3457e-3
#   12.3457e-5
#   12.3457e3

n. n=3:

300.1235e-1
123.4568e-4
123.4568e-6
123.4568e2
+2

, float, , , : 1/10 , ...

def unscientific_notation(n):
    rv = "%.5e" % (n / 10.0)
    rv = rv[0] + rv[2] + rv[1] + rv[3:]     # x.yz -> xy.z
    if rv.endswith("e+00"):    # handle 10..99 as specified
        rv = rv[:-4]
    return rv

1..9 - 5, 50e-1 , .

0

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


All Articles