![](/img/trans.png)
[英]How To Convert Number format from Scientific Notation to Number python?
[英]convert number to scientific notation python with a variable
我想使用str.format
將 2 數字轉換為提高到相同指數的科學記數法,但指數需要從str.format
中扣除。 例子:
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)
在這里,我有 m 有 e = 1 和 ye = 4,我想要的是兩者都具有相同的“e”。 我想將兩者都設置為指數 x。
我認為您必須自己計算,例如使用返回字符串的幫助程序 function:
def format_exp(x, n):
significand = x / 10 ** n
exp_sign = '+' if n >= 0 else '-'
return f'{significand:f}e{exp_sign}{n:02d}'
解釋:
x
是要格式化的數字, n
是要顯示的冪;significand
通過將x
除以 10 n ( 10 ** n
) 來計算要顯示在e
前面的部分;exp_sign
是+
或-
,取決於n
的值(復制默認行為)。示例用法:
>>> 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
您可以通過添加附加參數d
來設置有效數字部分中打印的小數位數(默認值為6
以重現默認 Python 行為)來增加此 function 的復雜性:
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}'
使用此 function,您可以控制打印的小數位數:
>>> 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.