Add Zeros To A Float After The Decimal In Python

Add zeros to a float after the decimal in Python

If you don’t know how to add zeros to a float after the decimal in Python, this article is perfect for you. Read the full article to find the right method for you.

How to add zeros to a float after the decimal in Python

Using format() method

Here, we will use the format() function, a simple way to add zeros to a float after the decimal point. Using the format() function, we will represent a float to format the number with exactly N digits which you want to amount zeros after the decimal point.

Let’s check out an example below to understand better.

Code example:

# Initialize a float number
floatNumber = 25.0

# Format float number with 3 zeros after the decimal point
res1 = format(floatNumber, '.3f')
print("Float number: ",res1)

# Format float number with 5 zeros after the decimal point
res2 = format(floatNumber, '.5f')
print("Float number: ",res2)

# Format float number with 8 zeros after the decimal point
res3 = format(floatNumber, '.8f')
print("Float number: ",res3)

Output:

Float number:  25.000
Float number:  25.00000
Float number:  25.00000000

Besides, you can write in another way as follows:

# Initialize a float number
floatNumber = 25.0

# Format float number with 3 zeros after the decimal point
print("Float number: ",'{0:.3f}'.format(floatNumber)) # 25.000

# Format float number with 8 zeros after the decimal point 
print("Float number: ","%.8f" % floatNumber) # 25.00000000

Output:

Float number:  25.000
Float number:  25.00000000

Notes: The format() function will return a string, so if you want to calculate, you need to convert it to a real number type by casting.

Code example:

# Initialize a float number
floatNumber = 25.0

# Format float number with 3 zeros after the decimal point
print("Type: ",type('{0:.3f}'.format(floatNumber))) # class 'str

# Format float number with 8 zeros after the decimal point
print("Type: ",type("%.8f" % floatNumber)) # class 'str

Output:

Type:  <class 'str'>
Type:  <class 'str'>

Using f-string formatting

We can use f-string formatting to add zeros after decimal pointing. Follow the code below to understand.

floatNumber = 25

# Format float number with 5 zeros after the decimal point
print("Float number: ",f'{floatNumber:.5f}') # 25.00000

# Format float number with 10 zeros after the decimal point
zeros = '.10f'
print ("Float number: ",f"{floatNumber:,{zeros}}") # 25.0000000000

Output:

Float number:  25.00000
Float number:  25.0000000000

Summary

The above are all the ways that can help you learn about how to add zeros to a float after the decimal in Python. If you have any questions, please leave a comment below. I will answer your questions as soon as possible.

Finally, thank you for reading this article, good luck, and see you again!

Maybe you are interested:

Leave a Reply

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