将指数浮点数舍入到小数点后两位 [英] round exponential float to 2 decimals

查看:56
本文介绍了将指数浮点数舍入到小数点后两位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Python 中将指数浮点数四舍五入为两位十进制表示.

4.311237638482733e-91 -->4.31e-91

你知道有什么快速的技巧可以做到这一点吗?
round(float, 2)"%.2f"%float 这样的简单解决方案不适用于指数浮点数:/

这不是关于舍入浮点数,而是舍入指数浮点数,因此它与 如何在 Python 中将数字四舍五入为有效数字

解决方案

您可以使用 g 格式说明符,它根据精度在指数和通常"表示法之间进行选择,并指定有效位数:

<预><代码>>>>%.3g"% 4.311237638482733e-91'4.31e-91'

如果您想始终以指数表示法表示数字,请使用 e 格式说明符,而 f 从不 使用指数表示法.此处描述了完整的可能性列表.

另请注意,您可以使用 str.format 代替 % 样式的格式:

<预><代码>>>>'{:.3g}'.format(4.311237638482733e-91)'4.31e-91'

str.format% 风格的格式更强大、更可定制,也更一致.例如:

<预><代码>>>>'' % []''>>>'' % 放()回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中类型错误:并非所有参数都在字符串格式化期间转换>>>''.格式([])''>>>''.format(set())''

如果您不喜欢在字符串文字上调用方法,您可以使用 format 内置函数:

<预><代码>>>>格式(4.311237638482733e-91,'.3g')'4.31e-91'

I want to round exponential float to two decimal representation in Python.

4.311237638482733e-91 --> 4.31e-91

Do you know any quick trick to do that?
Simple solutions like round(float, 2) and "%.2f"%float are not working with exponential floats:/

EDIT: It's not about rounding float, but rounding exponential float, thus it's not the same question as How to round a number to significant figures in Python

解决方案

You can use the g format specifier, which chooses between the exponential and the "usual" notation based on the precision, and specify the number of significant digits:

>>> "%.3g" % 4.311237638482733e-91
'4.31e-91'

If you want to always represent the number in exponential notation use the e format specifier, while f never uses the exponential notation. The full list of possibilities is described here.

Also note that instead of %-style formatting you could use str.format:

>>> '{:.3g}'.format(4.311237638482733e-91)
'4.31e-91'

str.format is more powerful and customizable than %-style formatting, and it is also more consistent. For example:

>>> '' % []
''
>>> '' % set()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting
>>> ''.format([])
''
>>> ''.format(set())
''

If you don't like calling a method on a string literal you can use the format built-in function:

>>> format(4.311237638482733e-91, '.3g')
'4.31e-91'

这篇关于将指数浮点数舍入到小数点后两位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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