convert number to scientific notation python with a variable

Viewed 422

I want to use str.format to convert 2 number to scientific notation raised to the same exponential but the exponential need to be set off the str.format. Example:

from math import log10
y=10000
x=round(np.log10(y))
m=10
y="{:e}".format(y)
m="{:e}".format(m)
print(y)
print(m)

here I have that m has e = 1 and y e = 4 and what I want is for both to have the same "e". i want to set both to exponencial x.

1 Answers

I think you have to calculate this yourself, for example using a helper function which returns a string:

def format_exp(x, n):
    significand = x / 10 ** n
    exp_sign = '+' if n >= 0 else '-'
    return f'{significand:f}e{exp_sign}{n:02d}'

Explanation:

  • x is the number to format, and n is the power that you want to display;
  • significand calculates the part to show in front of the e by dividing x by 10n (10 ** n);
  • exp_sign is either + or -, depending on the value of n (to replicate the default behaviour).

Example usage:

>>> import math
>>> y = 10000
>>> m = 10
>>> x = math.floor(math.log10(y))  # x = 4
>>> print(format_exp(y, x))
1.000000e+04
>>> print(format_exp(m, x))
0.001000e+04
>>> print(format_exp(y, 1))
1000.000000e+01
>>> print(format_exp(m, 1))
1.000000e+01

You can increase the complexity of this function by adding an additional parameter d to set the number of decimals printed in the significand part (with a default value of 6 to reproduce the default Python behaviour):

def format_exp(x, n, d=6):
    significand = x / 10 ** n
    exp_sign = '+' if n >= 0 else '-'
    return f'{significand:.{d}f}e{exp_sign}{n:02d}'

With this function, you can control the number of decimals printed:

>>> print(format_exp(y, x))  # default behaviour still works
1.000000e+04
>>> print(format_exp(y, x, 4))
1.0000e+04
>>> print(format_exp(y, x, 1))
1.0e+04
Related