# Format a float as an integer in Python Last updated: Sep 2, 2022 Photo from Unsplash

## Format a float as an integer in Python#

Use a formatted string literal to format a float as an integer, e.g. `result = f'{math.trunc(my_float)}'`. You can use expressions in f-strings to format the float as an integer by truncating or rounding.

main.py
```Copied!```import math

my_float = 378.656789

# ✅ format float as int by removing fractional part (truncating)
result = f'{math.trunc(my_float)}'
print(result)  # 👉️ 378

# ----------------------------------------------

# ✅ format float as int with rounding
result = f'{my_float:.0f}'
print(result)  # 👉️ 379

# ----------------------------------------------

# ✅ format float as int by rounding up
result = f'{math.ceil(378.000001)}'
print(result)  # 👉️ 379
``````

We used a formatted string literal to format a float as an integer.

The first example uses the `math.trunc()` method in a formatted string literal to remove the float's fractional part.
main.py
```Copied!```import math

my_float = 378.656789

result = f'Result: {math.trunc(my_float)}'
print(result)  # 👉️ Result: 378
``````

The math.trunc method takes a number, removes its fractional part and returns its integer part.

The `math.trunc()` method rounds towards zero.

main.py
```Copied!```import math

print(math.trunc(3.468))  # 👉️ 3
print(math.trunc(-3.468))  # 👉️ -3
``````

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with `f`.

main.py
```Copied!```my_str = 'The number is:'
my_int = 123

result = f'{my_str} {my_int}'
print(result)  # 👉️ The number is: 123
``````

Make sure to wrap expressions in curly braces - `{expression}`.

Formatted string literals also enable us to use the format-specific mini-language in expression blocks.

main.py
```Copied!```my_float = 378.656789

result = f'{my_float:.0f}'
print(result)  # 👉️ 379
``````

The digit after the period is the number of decimal places the number should have.

Notice that f-strings format with rounding.

You can use the `math.ceil()` method to round up when formatting the float as an integer.

main.py
```Copied!```import math

result = f'{math.ceil(378.000001)}'
print(result)  # 👉️ 379
``````

The math.ceil method returns the smallest integer greater than or equal to the provided number.

If you need to round down, use the `math.floor()` method.

main.py
```Copied!```import math

result = f'{math.floor(378.9999999)}'
print(result)  # 👉️ 378
``````

The math.floor method returns the largest integer less than or equal to the provided number.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer. You can use the search field on my Home Page to filter through all of my articles.