Skip to main content
Practice

format-function-floating-point

---
id: format-function-floating-point
title: Handling Floating-Point Numbers with the format() Function
description: How to display floating-point numbers in various formats in Python
tags:
- Floating-Point
- format function
- Python
- Programming
sidebar_position: 4
isPublic: false
---

# 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.

<br />

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.

```python title="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.