首页 > 解决方案 > 不带加号的科学记数法

问题描述

'{:e}'.format函数以“1e+06”的形式打印正值。

是否有其他格式将其显示为“1e6”(负指数显然为“1e-6”)?

或者是否需要自定义格式功能?

标签: pythonformatting

解决方案


您可以派生自己的string.Formatter子类:

import string


class MyFormatter(string.Formatter):
    def format_field(self, value, format_spec):
        if format_spec == 'm':
            return super().format_field(value, 'e').replace('e+', 'e')
        else:
            return super().format_field(value, format_spec)


fmt = MyFormatter()
v = 1e+06
print(fmt.format('{:e}, {:m}', v, v))  # -> 1.000000e+06, 1.000000e06

推荐阅读