简体   繁体   English

带有e +的python中的十进制数字

[英]decimal digits in python with e+

I want to do a print output in Python which gives everytime 2 digits. 我想用Python进行打印输出,每次输出2位。 The problem is, that there are very large (or small) numbers so normal Python output gives like this: 问题是,有很大(或很小)的数字,因此普通的Python输出如下所示:

5.89630388655e-09
8.93552349994e+14

but sometimes also normal numbers like: 但有时也有正常数字,例如:

345.8976

I just want to force it to have two digits, which means that the output for the large and small numbers are 我只想强制它具有两位数字,这意味着大号和小号的输出是

5.89e-09
8.93e+14

and the normal numbers just capped (or rounded) at the second digits: 普通数字仅以第二个数字为上限(或四舍五入):

345.89 (or 345.90)

How is that possible to realize in Python? 用Python如何实现?

In python you can format numbers in a way similar to other languages: 在python中,您可以采用类似于其他语言的方式设置数字格式:

print '%.2f' % number
print '%.3g' % number

See string formatting for more details on available flags and conversions. 有关可用标志和转换的更多详细信息,请参见字符串格式

Alternatively, you can use str.format() or a Formatter : 另外,您可以使用str.format()Formatter

'{0:.2f}'.format(number)
'{0:.3g}'.format(number)

See format string syntax for details on the format expression syntax. 有关格式表达式语法的详细信息,请参见格式字符串语法。

The f conversion produces notation which always contains the decimal point and may result in very long string representation for large numbers and 0.00 for very small numbers. f转换产生的符号始终包含小数点,并且对于大数可能会导致字符串表示非常长,对于小数会导致0.00表示。

The g conversion produces notation with or without the exponent depending on the size of the number. g转换会根据数字的大小产生带或不带指数的符号。 However, the precision argument is interpreted differently for g than for f conversion. 但是,对于g和对于f转换,精度参数的解释不同。 For f it is the number of digits after the decimal point while for g it is the number of all significant digits displayed. 对于f它是小数点后的位数。对于g它是显示的所有有效位数。 See string formatting for details. 有关详细信息,请参见字符串格式

The reason for the different interpretation of the precision argument is that when dealing with numbers of very different magnitudes it makes a lot more sense to stick to a fixed number of significant digits. 对precision参数进行不同解释的原因是,当处理数量级非常不同的数字时,坚持固定数量的有效数字会更有意义。

If you decide to not follow convention here, you'll need to write code which uses different formatting expressions for numbers of different magnitude. 如果您决定不遵循此处的约定,则需要编写针对不同数量的数字使用不同格式表达式的代码。 Note however that this will result in your code producing numbers with different accuracy depending on their magnitude, eg 345.89 has five significant digits while 3.46e+10 and 3.46e-10 only three. 但是请注意,这将导致您的代码根据其大小产生具有不同精度的数字,例如345.89具有五个有效数字,而3.46e + 10和3.46e-10只有三个有效数字。

You could use the format command: 您可以使用format命令:

"({0:.2f})".format(yournumber)

'.2f' means two decimal places '.2f'表示两位小数

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

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