简体   繁体   English

将科学计数法中的浮点数转换为“d.dd x 10^(-n)”

[英]Convert a float in scientific notation to a “d.dd x 10^(-n)”

I'm building a calculator to calculate some chemistry related calculations.我正在构建一个计算器来计算一些与化学相关的计算。 So most of the results will be extremely small values.所以大多数结果将是非常小的值。

An example result is 4.840909814726882e-09 .一个示例结果是4.840909814726882e-09

How do I display this value in a format like 4.84 x 10^(-9) ?如何以4.84 x 10^(-9)之类的格式显示此值?

try this:尝试这个:

format(4.840909814726882e-09, '.2e').replace('e', ' x 10^(') + ')'

Output: Output:
4.84 x 10^(-09)
It's not exactly the result you wanted but it's simple.这不完全是您想要的结果,但它很简单。

Also there is:还有:

def my_format(num):
    s = format(num, '.2e')
    base, exp = s.split('e')
    return f'{base} x 10^({int(exp)})'

Output: Output:

>>> my_format(4.840909814726882e-09)
'4.84 x 10^(-9)'

which is more coplicated but it's exectly the result you wanted.这更复杂,但这正是您想要的结果。

How do I display the value to a format like 4.84 x 10^(-9)?如何将值显示为 4.84 x 10^(-9) 之类的格式?

By hand, that is not a format supported by Python.手动,这不是 Python 支持的格式。

Although if you just want to "round off" the number because you neither have nor need 15 significant digits, then you can use format specifiers , and either the g presentation type:尽管如果您只是想“四舍五入”该数字,因为您既没有也不需要 15 个有效数字,那么您可以使用格式说明符g表示类型:

>>> format(v, 'g')
'4.84091e-09'

or an explicit precision:或明确的精度:

>>> format(v, '.3')
'4.84e-09'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM