以科学记数法显示小数 [英] Display a decimal in scientific notation

查看:62
本文介绍了以科学记数法显示小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何显示:

十进制('40800000000.00000000000000')为'4.08E+10'?

我已经试过了:

<预><代码>>>>'%E' % 十进制('40800000000.00000000000000')'4.080000E+10'

但它有那些额外的 0.

解决方案

from decimal import Decimal'%.2E' % 十进制('40800000000.00000000000000')# 返回 '4.08E+10'

在您的40800000000.00000000000000"中,有许多与任何其他数字具有相同含义的有效零.这就是为什么你必须明确告诉你想在哪里停下来.

如果您想自动删除所有尾随零,您可以尝试:

def format_e(n):a = '%E' % n返回 a.split('E')[0].rstrip('0').rstrip('.') + 'E' + a.split('E')[1]format_e(十进制('40800000000.00000000000000'))# '4.08E+10'format_e(十进制('40000000000.00000000000000'))#'4E+10'format_e(十进制('40812300000.00000000000000'))#'4.08123E+10'

How can I display this:

Decimal('40800000000.00000000000000') as '4.08E+10'?

I've tried this:

>>> '%E' % Decimal('40800000000.00000000000000')
'4.080000E+10'

But it has those extra 0's.

解决方案

from decimal import Decimal

'%.2E' % Decimal('40800000000.00000000000000')

# returns '4.08E+10'

In your '40800000000.00000000000000' there are many more significant zeros that have the same meaning as any other digit. That's why you have to tell explicitly where you want to stop.

If you want to remove all trailing zeros automatically, you can try:

def format_e(n):
    a = '%E' % n
    return a.split('E')[0].rstrip('0').rstrip('.') + 'E' + a.split('E')[1]

format_e(Decimal('40800000000.00000000000000'))
# '4.08E+10'

format_e(Decimal('40000000000.00000000000000'))
# '4E+10'

format_e(Decimal('40812300000.00000000000000'))
# '4.08123E+10'

这篇关于以科学记数法显示小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆