简体   繁体   中英

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.

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.

Alternative approach with 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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