Python

How to round a float in Python

December 16, 2021

How to round a float in Python

In this article we will learn how to round a float in Python, in a simple way, following the best practices of the language.

round a float in Python cover

What’s up programmer, okay? Let’s learn more about Python!

The float problem in Python is not necessarily Python’s

What happens is the way the floating point is saved on the CPU, as it works binary and not decimal

So it’s common to have problems like this:

sum = 0.1 + 0.2

print(sum) # 0.30000000000000004

To solve this with Python we have several alternatives

Basically, let’s format the number with the number of decimal places we want

Let’s see three options:

sum = 0.1 + 0.2

print("%.2f" % sum) # 0.30

print(round(sum,2)) # 0.3

print("{0:.3f}".format(sum)) # 0.300

So now we have the possibility of handling the float the way our software needs it, without suffering from processor inaccuracy 

Using these shapes, most of the time you will have the number you want.

But it could be that this small variation affects you at some level, according to the precision you need

But in most cases it works!

Conclusion

In this article we learned how to round a float in Python

And also that the problem is not caused by the language but by the way the value is saved by the CPU.

We use the float representation with “%.nf”, where n is the number of decimal places

The round method, which is widely used in other languages, and finally the format, which formats the number based on a pattern that we pass as a parameter.

Want to learn more about Python? Click here!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x