-1

I would like to format these numbers to the corresponding format:

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

... but I can't figure out how to do this elegantly.

Thanks for any help solving this.

saturnusringar
  • 149
  • 3
  • 13
  • In which country format? – shafik May 20 '19 at 08:32
  • Possible duplicate of this [post](https://stackoverflow.com/questions/16670125/python-format-string-thousand-separator-with-spaces) and this [one](https://stackoverflow.com/questions/1823058/how-to-print-number-with-commas-as-thousands-separators) – Alexandre B. May 20 '19 at 08:34
  • See the formatting infos here: https://stackoverflow.com/questions/16670125/python-format-string-thousand-separator-with-spaces - – xph May 20 '19 at 08:34
  • @shafik I'm using swedish – saturnusringar May 20 '19 at 08:38
  • See the 1st note https://docs.djangoproject.com/en/dev/topics/i18n/formatting/#overview – shafik May 20 '19 at 08:40
  • Possible duplicate of [python format string thousand separator with spaces](https://stackoverflow.com/questions/16670125/python-format-string-thousand-separator-with-spaces) – funie200 May 20 '19 at 08:40
  • Yes, the question doesn't have all research info, but it has `django` tag in it, and django does have a simple solution, see my answer below. – vishes_shell May 20 '19 at 08:41

1 Answers1

3

You can use 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
vishes_shell
  • 22,409
  • 6
  • 71
  • 81
  • Excellent solution, but one more thing is needed to always get two decimals: `decimal_pos=2` ... perhaps you want to edit your answer? – saturnusringar May 20 '19 at 08:48
  • @saturnusringar i've updated an answer before you wrote your comment.:) Glad that we are on the same page.:) Good luck with formatting swedish numbers.:) – vishes_shell May 20 '19 at 08:51