Skip to main content
Crowdfunding
Python + AI for Geeks
Practice

Handling Floating-Point Numbers with the format() Function

To output real numbers with decimals, use {:f}.

The f Inside the curly braces, a format specifier is used to output floating-point (decimal) numbers.

In programming, floating-point number refers to a real number in which the decimal point can move (or float) within the number.


By using .number to the right of the colon :, you can specify the number of decimal places.

For example, {:.2f} will only display two decimal places of the given real number.

Floating point formatting example
float_number = 123.4567
formatted_float = "float_number: {:.2f}".format(float_number)

print(formatted_float) # "float_number: 123.46"

Outputting in Scientific Notation

Use {:e} to display floating-point numbers in scientific notation using exponents.

For example, displaying 123.456789 in scientific notation would give 1.23e+02.

Scientific notation example
float_number = 123.456789

scientific_formatted = "{:.2e}".format(float_number)

print(scientific_formatted) # "1.23e+02"

Removing Decimal Places

To remove the decimal places from a floating-point number, use :.0f.

Removing insignificant decimals
number = 123.0

formatted_number = "{:.0f}".format(number) # No decimal places displayed

print(formatted_number) # "123"

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.