Round a float to the nearest 10th (0.1) in Python

avatar

Borislav Hadzhiev

Last updated: Jul 12, 2022

banner

Photo from Unsplash

Round a float to the nearest 10th (0.1) in Python #

Use the round() function to round a float to the nearest 10th (0.1), e.g. result = round(4.5678, 1). The round() function will return the number rounded to 1 digit precision after the decimal point.

main.py
# ✅ round a float to the nearest 10th (0.1) result_1 = round(4.5678, 1) print(result_1) # 👉️ 4.6 result_2 = round(4.1234, 1) print(result_2) # 👉️ 4.1 # ------------------------------- # ✅ print a float rounded to the nearest 10th (0.1) my_float = 4.5678 my_str_1 = f'{my_float:.1f}' print(my_str_1) # 👉️ '4.6' my_str_2 = f'{my_float:.2f}' print(my_str_2) # 👉️ '4.57'

The round function takes the following 2 parameters:

NameDescription
numberthe number to round to ndigits precision after the decimal
ndigitsthe number of digits after the decimal, the number should have after the operation (optional)
The round function returns the number rounded to ndigits precision after the decimal point.

If ndigits is omitted, the function returns the nearest integer.

main.py
my_num = 3.456 result_1 = round(my_num) print(result_1) # 👉️ 3 result_2 = round(my_num, 1) print(result_2) # 👉️ 3.5

If you need to print a floating-point number rounded to the nearest 10th (0.1), use a formatted string literal.

main.py
my_float = 4.5678 my_str_1 = f'{my_float:.1f}' print(my_str_1) # 👉️ '4.6' my_str_2 = f'{my_float:.2f}' print(my_str_2) # 👉️ '4.57'
Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.
main.py
my_str = 'is subscribed:' my_bool = True result = f'{my_str} {my_bool}' print(result) # 👉️ is subscribed: True

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

We are also able to use the format specification mini-language in expressions in f-strings.

main.py
my_float = 1.45678 result_1 = f'{my_float:.1f}' print(result_1) # 👉️ '1.5' result_2 = f'{my_float:.2f}' print(result_2) # 👉️ '1.46' result_3 = f'{my_float:.3f}' print(result_3) # 👉️ '1.457'

The f character between the curly braces stands for fixed-point notation.

The character formats the number as a decimal number with the specified number of digits following the decimal point.

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