Python formatting large values

前端 未结 2 924
旧时难觅i
旧时难觅i 2021-01-15 14:24

Below is the code for formatting an x value that I have been using.

Examples of what does it do:

  • It formats 7,500,000 into 7.5 M
  • It form

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-15 15:00

    Try all the different possible ways to format it and pick the shortest one length-wise, with preference given to larger units (e.g., prefer .55 B to 550 M, since they are the same length).

    As for stripping leading zeros, one possible solution is checking if s[:2] == '0.' and replacing it with '.'

提交回复
热议问题