format number in python

There are several ways to format numbers in Python:

  1. Using the format() method:
main.py
num = 1234.56789
print("Formatted number: {:.2f}".format(num))
63 chars
3 lines

Output:

main.py
Formatted number: 1234.57
26 chars
2 lines
  1. Using f-strings (Python 3.6+):
main.py
num = 1234.56789
print(f"Formatted number: {num:.2f}")
55 chars
3 lines

Output:

main.py
Formatted number: 1234.57
26 chars
2 lines
  1. Using the round() method:
main.py
num = 1234.56789
formatted_num = round(num, 2)
print("Formatted number:", formatted_num)
89 chars
4 lines

Output:

main.py
Formatted number: 1234.57
26 chars
2 lines
  1. Using the locale module:
main.py
import locale

num = 1234.56789
locale.setlocale(locale.LC_ALL, 'en_US.utf-8')
formatted_num = locale.currency(num, grouping=True)
print("Formatted number:", formatted_num)
173 chars
7 lines

Output:

main.py
Formatted number: $1,234.57
28 chars
2 lines

Note that the locale module formats the number according to the current locale settings of your operating system.

gistlibby LogSnag