# 如何在python中用有限的有效数字和千位分隔符格式化整数

[英]How to format an integer in python with limited significant figures AND thousands separators

Task: format a (large) integer in python with limited significant figures and thousands separators.任务：在python中用有限的有效数字和千位分隔符格式化一个（大）整数。

For example, turn例如，转

``````791075165588
``````

into进入

``````791,000,000,000
``````

The cleanest solution I can find is:我能找到的最干净的解决方案是：

``````print('{:,}'.format( int( float ('%.3g' % 791075165588 ) ) )   )
``````

Output:输出：

``````791,000,000,000
``````

Replace the `3` with the desired number of significant figures.`3`替换为所需的有效数字位数。

Alternative approach with numpy: numpy 的替代方法：

``````print(   '{:,}'.format(  (lambda n, f : np.round(n, f - len(str(abs(int(n)))) ) ) (791075165588 , 3)   )    )
``````

You seem to have already a solution working for your own purposes.您似乎已经有一个适合您自己目的的解决方案。 If someone would want to choose significant figures from the nearest thousands/millions, rather than choosing the number of significant figures, they could do this:如果有人想从最接近的千位/百万位中选择有效数字，而不是选择有效数字的位数，他们可以这样做：

``````import numpy as np
mynumber = 791075165588

print(f'Rounding to -9 means billions, for instance {np.round(mynumber, -9):,}')
``````
``````Rounding to -9 means billions, for instance 791,000,000,000
``````

That was limited to the billions significant figures.这仅限于数十亿的重要数字。