Ways For Using F-Strings To Format Floats To N Digits After Decimal In Python

Most developers prefer using f-strings to format floats to N digits after decimal in Python. It is a convenient way to print the floats with a customizable number of digits after decimal. In this article, we will share with you several ways to use the f-strings for this work.

Using f-strings to format floats to N digits after decimal

Here are some easy ways for using f-strings to format floats to N digits after decimal in Python.

Put the float in the f-strings directly

You can put the float in the f-strings directly without creating a variable. This f-strings literal takes the float and transforms it in the format with the specific digits after decimal, as you decide.

The syntax of f-strings is like this:

f'{[parameter]:.[N]f}'

You need to put the float number as the [parameter]

For the [N], you need to write a positive integer. It means how many digits after decimal you want to print out. For example, if you choose 2 as the [N], the float will be formatted to a number with 2 digits after the decimal.

Here is the code sample:

# Format the float 3.324234 to the 3.324 (3 digits after the decimal)
print(f'{3.324234:.3f}')

The output will be:

3.324

Create a float variable and use the variable as parameter in the f-strings

You can also create a variable with a float value. The f-strings also work with a float variable. This string literal returns the same formatted value as you customize.

The syntax is like this:

f'{[variable]:.[N]f}'

You put the float variable in the [variable].

For the [N], you still put a positive integer to decide the number of digits after the decimal.

Here is the code sample:

# Create a float variable
fltNumber = 5.32423492

# Format the float 5.32423492 to 2 digits after the decimal
print(f'{5.32423492:.2f}')

The output will be:

5.22

Do a math of floats in the f-strings

f-strings still work properly, even when you do math inside the {}. The f-strings literals take the result of the math and format it.

The syntax is like this:

f'{[math of floats]:.[N]f}'

The parameter is a math of different floats. The result will be formatted to have the [N] number of digits after decimal as you choose.

Here is the code sample:

print("float1: 5.32423492")
print("float2: 2.3423432")
print("float1 + float2: ", 5.32423492 + 2.3423432)

# Format the float 5.32423492 to 2 digits after the decimal
print("Result:", f'{5.32423492 + 2.3423432:.2f}')

The result will be:

float1: 5.32423492
float2: 2.3423432
float1 + float2:  7.6665781200000005
Result: 7.67

Summary

To summarize, we have given you the 3 ways of using f-strings to format floats to N digits after decimal in Python. You can either put a float variable or add a float directly inside the {} of the f-strings. Also, these string literals support doing the math of floats and formatting the result.

Leave a Reply

Your email address will not be published. Required fields are marked *