Skip to content
Home » How to Check the Number of Digits of a Number

How to Check the Number of Digits of a Number

Spread the love

Today I’ll show you how to quickly check the length of a number. And by the length of a number I mean the number of digits that make up the number.

So, it’s pretty easy. To check how many digits there are in a number, we can convert the number to a string and then use the len function to check its length:

>>> len(str(1000))
4
>>> len(str(5 ** 1000))
699
>>> len(str(2 ** 500000))
150515

We must be careful with floats, though:

>>> len(str(5.0))
3

Not only the digits are counted here, but also the decimal point. This is why the result is 3. The problem with floats is that there’s a limited precision and the result may be wrong. You can always convert the result to an integer like so:

>>> int(2.5)
2

and check how many digits there are without the fractional part:

>>> len(str(int(2.5 * 2)))
1

or another example:

>>> len(str(int(17.21 * 3.541)))
2

There are only two digits before the decimal point, which you can easily check:

>>> 17.21 * 3.541
60.94061

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

Here’s the video version:


Spread the love

Leave a Reply