【问题标题】:Format number with space as thousands separator and comma for decimals格式化数字,空格作为千​​位分隔符,逗号作为小数
【发布时间】:2019-05-20 08:22:57
【问题描述】:

我想把这些数字格式化成相应的格式:

3911.940 -> 3 911,94
1970 -> 1 970,00
393.75000 -> 393,75
300000.50 -> 300 000,50

...但我不知道如何优雅地做到这一点。

感谢您为解决此问题提供的任何帮助。

【问题讨论】:

标签: python django


【解决方案1】:

你可以使用django.utils.numberformat.format:

>>> from django.utils import numberformat
>>> for i in [3911.940, 1970, 393.75000, 300000.50]:
...     print(i, ' -> ', numberformat.format(i, decimal_sep=',', decimal_pos=2, grouping=3, thousand_sep=' ', force_grouping=True))
...
3911.94  ->  3 911,94
1970  ->  1 970,00
393.75  ->  393,75
300000.5  ->  300 000,50

【讨论】:

  • 出色的解决方案,但还需要一件事才能始终获得两位小数:decimal_pos=2 ...也许您想编辑您的答案?
  • @saturnusringar 在你写评论之前我已经更新了一个答案。:) 很高兴我们在同一页上。:) 祝你好运格式化瑞典数字。:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-03
  • 2020-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-26
相关资源
最近更新 更多