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
Here’s the video version: