Formatting numbers in Python refers to displaying numbers in a more readable and presentable way. Instead of showing long strings of digits, we can format numbers to add commas, round decimals, specify precision, and more.

There are several methods for formatting numbers in Python:

  1. The str.format() method
  2. f-strings
  3. The % operator
  4. The round() function
  5. Python‘s numeric literals

In this comprehensive guide, we‘ll explore these techniques with code examples to format integers, floats, decimal places, add separators, pad with zeros, and work with numeric representations.

The str.format() Method

The str.format() method allows us to format and place values inside a string. We pass the values we want formatted inside the curly braces {} and specify presentation details.

Here‘s an example:

num = 45678.456
print(‘The number is: {:,.2f}‘.format(num))

Output:

The number is: 45,678.46

The : after the opening brace adds comma separators between thousands. The ,.2f formats the number to 2 decimal places.

Some common str.format() number presentations:

  • {:.2f} – Float with 2 decimals
  • {:,} – Thousands separator
  • {:.0f} – Integer (no decimals)
  • {:b} – Binary format
  • {:%} – Percentage

Format Floating Point Numbers

When formatting floats, we can control the precision with:.2f, .3f etc for decimal places.

pi = 3.14159
print(‘{:.4f}‘.format(pi))

Output:

3.1416

We can remove decimal points altogether with:.0f:

print(‘{:.0f}‘.format(pi))

Output:

3

Format with Commas

Large numbers are easier to read with comma separators between thousands positions. We get this with : ,

large_num = 34890345  
print(‘{:,}‘.format(large_num))

Output:

34,890,345

Format as Percentage

To convert to a percentage, use:% after a .precision f

decimal = 0.826
print(‘{:.2%}‘.format(decimal))  

Output:

82.60%

Format with Leading Zeros

We can pad integer strings with leading 0s to match a certain length by specifying a width.

Use 0>n where n is the final string length:

num = 42
print(‘{:0>5d}‘.format(num))

Output:

00042

5 digits specified, padded with leading zeros.

Using f-strings

Python f-strings provide an easier way to embed expressions inside string literals for formatting.

We prefix the string with f and use {} brackets for inserting expressions:

name = ‘Fred‘
print(f‘He said his name is {name}.‘) 

Output:

He said his name is Fred.

To format numbers, we pass the formatting after the expression inside the brackets.

Example decimal places:

pi = 3.14159
print(f‘Pi to 3 decimal places: {pi:.3f}‘)

Output:

Pi to 3 decimal places: 3.142

f-strings provide the same formatting options as str.format(), like commas, percentages, leading zeros etc.

Some examples:

sales = 34890345
print(f‘Sales: {sales:,}‘)

percent = 0.825  
print(f‘Percentage: {percent:.2%}‘)

value = 485
print(f‘Leading zeros: {value:0>6d}‘) 

Output:

Sales: 34,890,345
Percentage: 82.50%  
Leading zeros: 000485

The % Operator

Before f-strings and str.format(), the % operator was used to format strings.

It is similar to str.format() but less flexible since formatting is specified directly after the % instead of inside the string.

num = 45678.456
print(‘The number is %.2f‘ % num) 

Output:

The number is 45678.46

We can still format floats, integers, decimals etc.

num = 3.14159
print(‘Pi to 3 decimal places: %.3f‘ % num)
print(‘Pi as integer: %.0f‘ % num)

Output:

Pi to 3 decimal places: 3.142
Pi as integer: 3

While % formatting works, str.format() and f-strings are more Pythonic and offer more control.

The round() Function

The built-in round() function rounds a floating point number to a given precision in decimal places (default is 0 decimal places, to nearest integer).

We pass the number as the first argument, and optionally the number of decimals as the second argument.

Examples:

num = 45678.456

print(round(num)) 
# 45678

print(round(num, 2))
# 45678.46

round() is useful when we want to eliminate decimal points, not just trim them. Compare to formatting which would keep trailing zeros.

num = 100.0
print(‘%.1f‘ % num) # 100.0 - formatting keeps trailing 0

print(round(num, 1)) # 100.0 - rounded value  

Note that round() converts to float if passed an integer, unlike int() which converts to integer:

num = 100
print(round(num, 1)) # 100.0 now float
print(int(num)) # 100 remains integer 

Python Numeric Literals

Python has several numeric literal forms for specifying different bases and separators.

Underscores as Separators

We can make large integer literals more readable by using _ as a thousands separator:

val = 1_000_000_000   
print(val)

Output:

1000000000

Python ignores the underscores and interprets the integer value normally.

Binary, Octal, Hex Literal Forms

Integer literals can be written in binary with a 0b prefix, octal with 0o, and hexadecimal with 0x:

val1 = 0b101010 # Binary
val2 = 0o52 # Octal  
val3 = 0x2af # Hexadecimal

print(val1, val2, val3)

Output:

42 42 687

The binary, octal and hex formats make working with numeric bases easier.

We can combine literals and format() to convert integers between number systems:

num = 255

print(f‘Hex: {num:x}‘)
print(f‘Binary: {num:b}‘) 
print(f‘Octal: {num:o}‘)

Output:

Hex: ff
Binary: 11111111
Octal: 377

Putting Formatting to Use

Now that we‘ve covered different methods to format numbers in Python, let‘s look at some practical examples and sample use cases.

Round Floats from Calculations

It‘s common to round floats after doing calculations to standard precision:

avg = sum(num_list) / len(num_list)
print(‘Average score: {:.2f}‘.format(avg)) 

area = 3.14 * radius**2  
print(f‘Circle area: {round(area, 1)}‘)

Format Currency Values

When dealing with money and pricing, we‘ll want to format with 2 decimal points and thousand separators:

price = 34890.345
print(f‘The price is: {price:,.2f}‘)

Output:

The price is: 34,890.35

Format Percentages

Formatting percentages makes it clear when displaying fractional values:

completion = 0.7485
print(‘Progress: {:.0%}‘.format(completion))

Output:

Progress: 75%

Clean Up Number Strings

When reading in values from files or user input, they may contain extra chars we want to strip out:

dirty = ‘$100.00‘
num = float(dirty.replace(‘$‘, ‘‘))

print(‘{:.2f}‘.format(num)) 

Output:

100.00

Here we formatted the cleaned float num.

Define Number String Widths

Padding strings with zeros or limiting precision is useful for:

  • Formatted reports/tables
  • Ensuring data matches formats
  • Balancing decimal points in columns
for num in table_col:
   print(‘{:0>5.2f}‘.format(num)) # Pad to 5 chars  

Highlight Numeric Differences

Compare numbers by showing a readable diff as +/- percentage:

old = 10500
new = 10015 

diff = ((new - old) / old) * 100 

dir = ‘lower‘ if diff < 0 else ‘higher‘

print(f‘{dir}: {"-" if dir == "lower" else "+"}{abs(diff):.2f}%‘)

Output:

lower: -4.57% 

There are many possibilities through utilizing Python‘s formatting mini-language!

Conclusion

Formatting numbers in Python provides greater control over how values are presented as strings. Converting numbers to readable formats can improve code clarity and precision.

Key takeaways include:

  • str.format() offers flexible formatting by passing info inside the curly braces
  • f-strings provide concise syntax for embdedding expressions in strings
  • round() handles rounding decimals rather than just truncating them
  • Underscores can be used as thousands separators for large numbers
  • prefix 0b, 0o, 0x represent binary, octal and hex literals
  • Multiple approaches allow handling integers, floats, precision, padding

There are also many other formatting options for alignment, numeric representations and more.

Overall, through leveraging formats we can display numbers exactly how we need them for output or processing in Python programs.

Similar Posts