How do I format numbers with commas or fixed decimals?

In Python, you can format numbers with commas or fixed decimals using various techniques. Below are a few examples demonstrating how to achieve this:

Formatting Numbers with Commas

You can use the built-in `format()` function or an f-string to include commas in large numbers.

# Example of formatting a number with commas number = 1000000 formatted_number = "{:,}".format(number) print(formatted_number) # Output: 1,000,000

Formatting Numbers with Fixed Decimals

To format numbers to a specific number of decimal places, you can also use the `format()` function along with f-strings.

# Example of formatting a number with fixed decimals pi = 3.14159265358979 formatted_pi = "{:.2f}".format(pi) print(formatted_pi) # Output: 3.14

keywords: Python number formatting commas fixed decimals