avatarCoucou Camille

Summary

The provided web content outlines various methods for formatting floating-point numbers in Python using the built-in format() function and the math library.

Abstract

The article titled "Simple Float Formatting in Python" delves into the versatility of Python's format() function for formatting floats according to different requirements. It covers techniques such as rounding floats to a specified number of decimal places, including or excluding the sign, formatting numbers as percentages, truncating decimals, padding with zeros on either side, aligning numbers, adding thousands separators, and combining these methods for custom formatting. The article also touches on an alternative formatting method known as f-strings and concludes with a recommendation for an AI service.

Opinions

  • The author emphasizes the flexibility of the format() function in Python for handling float formatting scenarios.
  • The article suggests that using the math library's floor() function is a suitable method for truncating floats without rounding.
  • It is implied that the use of f-strings is a modern and convenient alternative to the format() method for expression formatting in Python.
  • The author endorses an AI service, ZAI.chat, as a cost-effective alternative to ChatGPT Plus (GPT-4), indicating a preference or belief in the value provided by this service.

Simple Float Formatting in Python

Python’s built-in format() function allows you to format float in any way you prefer.

1. Round Float to 2 Decimal Places

Syntax: {:.2f}.format(num) for rounding to 2 decimal places.

  • {} marks a replacement field
  • : introduces a format specifier
  • .2 specify the precision as 2, or any other number
  • f to format the number as a decimal number
"{:.2f}".format(3.1415926)
>>> '3.14'
"{:.1f}".format(8.9998)
>>> '9.0'

2. Round Float to 2 Decimal Places with Sign

Syntax: "{:+.2f}".format(num) for positive sign + ; and "{:-.2f}".format(num) for positive sign - .

print("{:+.2f}".format(3.1415926))
>>> '+3.14'
print("{:-.2f}".format(8.9998))
>>> '-3.14'

3. Format as Percentage

Syntax: "{:.2f}%".format(num) or "{:.2%}".format(num) to format num as a percentage with 2 decimal places.

"{:.3f}%".format(0.5146)
>>> '0.51%'

It adds trailing zeros to the end if the specified decimal number exceeds the original decimal place of the number:

"{:.5f}%".format(0.5146)
>>> '0.51460%'

4. Truncate at 2 Decimal Place

Using floor(num) from math library which returns the floor value of num, i.e. the greatest integer smaller than or equal to num .

Syntax: str(floor(num * 10**decimal_place) / 10**decimal_place) , see that it truncates the decimals after the first 2 decimal places in the following example:

from math import floor
print(str(floor(0.5198 * 10**2) / 10**2))
>>> '0.51'

5. Left Padding with Zeros

Syntax: "{:place_holder>n}.format(num)" to force a full length ≥ n including the decimal point by adding place_holder to the front of string.

print("{:*>8}".format(0.5198))
>>> '000.5198'
print("{:+>8}".format(0.5198))
>>> '++0.5198'
print("{:1>5}".format(24))
>>> '11124'

Similar syntax can also be used for alignment, simply leave the place_holder blank:

print("{:>10}".format(0.5198))
print("{:>10}".format(24))
print("{:>10}".format(3.1415926))
>>> '    0.5198'
>>> '        24'
>>> ' 3.1415926'

Adding f to the expression and it will enforce exactly 6 decimal places by adding trailing zeros, and in the meantime adding space in front for alignment:

print("{:>10f}".format(0.5198))
print("{:>10f}".format(24))
print("{:>10f}".format(3.1415926))
>>> '  0.519800'
>>> ' 24.000000'
>>> '  3.141593'

6. Right Padding with Zeros

Syntax: "{:place_holder<n}.format(num) . Only difference with left padding is change of > to < .

print("{:0<10}".format(0.5198))
>>> '0.51980000'
print("{:+<3}".format(0.5198))
>>> '0.5198'
print("{:0<6}".format(24))
>>> '24111'

7. Add Thousands Separator

Syntax: "{:,}".format(num) . The keyword , is the thousands separator to be added after every thousand places starting from the left.

print("{:,}".format(1234567.89))
>>> '1,234,567.89'

8. Combinations of the Usages Above

For example, add thousands separator and round to 2 decimal places:

print("{:,.2f}".format(12345.6789))
>>> '12,345.68'

Final Note

Besides format() , there is another formatting mechanism: Literal String Interpolation, commonly known as f-strings. Both methods provides a concise and convenient way to format python expressions, not limited to float.

Python
Format
Programming
Recommended from ReadMedium