Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count the number of zeros in a decimal?

Tags:

python

What is the most efficient way to calculate the number of 0s in a decimal before the first non 0 number?

Desired outcome:

0.0000456 ---> 4
0.00406 ---> 2
0.000456 ---> 3

So far I have tried mathematically this (which is slow):

from math import floor, log

def num_zeros(decimal):
    return 10 - floor(log(decimal *10e10,10))

and this (which is not right as 0 after a first number will be counted):

def count_0(number):
    n = format(number, 'f').count('0')
    return n - 1
like image 245
Paco Casnueva Avatar asked Oct 31 '25 22:10

Paco Casnueva


2 Answers

Why not simply:

from math import floor, log10, inf

def num_zeros(decimal):
    return inf if decimal == 0 else -floor(log10(abs(decimal))) - 1

This handles 0.001 correctly (2 zeros), whereas some answers would print 3. It also now works for negative numbers and zero.

I'd be shocked if string methods were faster.


To handle non-finite numbers correctly as well, simply swap out the definition of floor as follows:

def floor(decimal):
    return math.floor(decimal) if math.isfinite(decimal) else decimal

Or equivalently:

from math import floor, log10, inf, isinf, nan, isnan

def num_zeros(decimal):
    if isnan(decimal):
        return nan
    if isinf(decimal):
        return -inf
    return inf if decimal == 0 else -floor(log10(abs(decimal))) - 1
like image 140
Hans Brende Avatar answered Nov 02 '25 11:11

Hans Brende


Here's a way to approach this using a regular expression:

# Update, simplified sol thanks to @Aran-Fey's comments
import re
s = '0.0000456'
len(re.search('\d+\.(0*)', s).group(1))
#4
like image 20
yatu Avatar answered Nov 02 '25 12:11

yatu