5

Easy task:

number = 100123.44
number_formated = "100,123"

Don't tell me there is no better way than:

number_formated = "{:,}".format(int(format("{:.0f}".format(number))))

?

VengaVenga
  • 680
  • 1
  • 10
  • 13

3 Answers3

11

To get the number with , as a thousands separator as a whole number, use this format string:

number_formated = "{:,.0f}".format(number)

No need to nest two calls and cast the resulting string to int again.

Christian König
  • 3,437
  • 16
  • 28
3

You can simply call int on your number without formatting:

number_formatted = "{:,}".format(int(number))

If you use Python 3.6 or higher you can use f-strings:

number_formatted = f'{int(number):,}'

Edit: using Christian König answer we can remove the int call:

number_formatted = f"{number:,.0f}"
ikkuh
  • 4,473
  • 3
  • 24
  • 39
  • 2
    Note that `int(number)` truncates the decimal digits, while `f"{number:,.0f}"` rounds. `int(1.9)` gives `1`, but `f"{1.9:,.0f}"` gives `2`. – Aran-Fey Oct 05 '18 at 09:24
-1

You can use this formatted_number = "{:,}".format(number)

tank1610
  • 49
  • 2