将科学计数法分配给 Python 中的变量
Assign scientific notation to variable in Python
我正在尝试请求一个 float 变量,然后为其分配科学记数法,然后在以下操作中使用该记数法。比如,我希望程序能够真正使用符号,而不仅仅是 return 其中的结果。
我设法使用打印功能转换变量:
def estim(abs(x)):
a=print("{:.3e}".format(x))
return a
然而,这实际上并没有赋予 x 科学价值。然后我尝试了
b=float(a)
但是a是None类型的,所以不行。有帮助吗?
编辑:按照科学记数法,我的意思是 X.YYYe+Z,
示例:31234.34234 -> 3.12e+04
如果你这样做"{:.3e}".format(x)
你会得到小数点后3位,即
>>> a = 31234.34234
>>> "{:.3e}".format(a)
'3.123e+04'
要得到你想要的,你需要做 "{:.2e}".format(x)
。
>>> "{:.2e}".format(a)
'3.12e+04'
>>> float("{:.2e}".format(a))
31200.0
将其转换回 float
将为您提供原始值
作为函数
def estim(x):
x = abs(x)
a=("{:.2e}".format(x))
print(a)
return a
提示:
您可以使用 %
(它可能已被弃用)
>>> a = 31234.34234
>>> "%e"%a
'3.123434e+04'
打印的返回值始终是 None 我怀疑您需要的更多是:
def estim(x):
a="{:.3e}".format(abs(x))
print a
return a
您需要使用a="{:.3e}".format(x)
这是一个例子
x=246789;
a="{:.3e}".format(x);
print a;
print float(a);
输出
2.468e+05
246800.0
我正在尝试请求一个 float 变量,然后为其分配科学记数法,然后在以下操作中使用该记数法。比如,我希望程序能够真正使用符号,而不仅仅是 return 其中的结果。 我设法使用打印功能转换变量:
def estim(abs(x)):
a=print("{:.3e}".format(x))
return a
然而,这实际上并没有赋予 x 科学价值。然后我尝试了
b=float(a)
但是a是None类型的,所以不行。有帮助吗?
编辑:按照科学记数法,我的意思是 X.YYYe+Z, 示例:31234.34234 -> 3.12e+04
如果你这样做"{:.3e}".format(x)
你会得到小数点后3位,即
>>> a = 31234.34234
>>> "{:.3e}".format(a)
'3.123e+04'
要得到你想要的,你需要做 "{:.2e}".format(x)
。
>>> "{:.2e}".format(a)
'3.12e+04'
>>> float("{:.2e}".format(a))
31200.0
将其转换回 float
将为您提供原始值
作为函数
def estim(x):
x = abs(x)
a=("{:.2e}".format(x))
print(a)
return a
提示:
您可以使用 %
(它可能已被弃用)
>>> a = 31234.34234
>>> "%e"%a
'3.123434e+04'
打印的返回值始终是 None 我怀疑您需要的更多是:
def estim(x):
a="{:.3e}".format(abs(x))
print a
return a
您需要使用a="{:.3e}".format(x)
这是一个例子
x=246789;
a="{:.3e}".format(x);
print a;
print float(a);
输出
2.468e+05
246800.0