将数字转换为字符串科学计数法固定长度 [英] Convert number to string scientific notation fixed length
问题描述
我有一个正常的浮点数,例如"1234.567"或"100000".我想将其转换为字符串,以便精度是固定的并且数字是科学计数法.例如,使用5位数字,结果分别为"1.2346e003"和"1.0000e005".如果可以的话,内置的十进制数->字符串函数将对它进行四舍五入,因此即使我使用第二个数字也只能是"1e005"想要更多数字.这是不可取的,因为我需要所有数字都相同长度.
I have a normal float number such as "1234.567" or "100000". I would like to convert it to a string such that the precision is fixed and the number is in scientific notation. For example, with 5 digits, the results would be "1.2346e003 and "1.0000e005", respectively. The builtin Decimal number -> string functions will round it if it can, so the second number would be only "1e005" even when I want more digits. This is undesirable since I need all numbers to be the same length.
是否有一种"pythonic"的方法来执行此操作而无需进行复杂的字符串操作?
Is there a "pythonic" way to do this without resorting to complicated string operations?
推荐答案
precision = 2
number_to_convert = 10000
print "%0.*e"%(precision,number_to_convert)
这是您要的吗?
这篇关于将数字转换为字符串科学计数法固定长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!