Python

How to limit decimal numbers in Python?

December 27, 2021

How to limit decimal numbers in Python?

In this article, we’ll learn how to limit decimal numbers in Python, in a simple way with Python’s own resources.

limit decimal numbers in Python cover

Hey you programmer, okay? Let’s learn more about Python!

We can solve this problem by rounding the number with the round function, for example

Let’s see it in practice:

n = round(3.32424, 2)
print(n) // 3.32

The first argument is the number to be rounded and the second is how many decimal places we want to display

We can also format the number, also choosing how many places to display, let’s see it:

n2 = 4.38991
print("%.2f" % n2) // 4.39

So we use a special Python syntax to format the number the way we need it.

You can also use the format feature, which came in Python version 3

Making it even easier to format the number with decimal places, see it running:

t = 7.98562434234
print('The value is {:.4f}'.format(t))

Very similar to our second example, but this one is already included in the print

And its syntax is also easy to understand, we can decide the number of places

Conclusion

In this article we learned how to limit decimal numbers in Python

We use the round function that accepts as parameters the number in float and also how many places we want it to be rounded

We also learned another way of formatting the number, using a special Python syntax.

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