Given a string representing a real number in decimal, how can I count the number of needed (non-zero) decimal places?

python

Solution

You can use a regex to parse `value`, capture the decimal digits and count the length of the match, if any:

import re

def num_decimal_places(value):
    m = re.match(r"^[0-9]*\.([1-9]([0-9]*[1-9])?)0*$", value)
    return len(m.group(1)) if m is not None else 0

this is a bit less "raw" than splitting the string with multiple `if else`, not sure if simpler or more readable, though.

Problem

How would I do the following: ``` >>> num_decimal_places('3.2220') 3 # exclude zero-padding >>> num_decimal_places('3.1') 1 >>> num_decimal_places('4') 0 ``` I was thinking of doing: ``` len((str(number) if '.' in str(number) else str(number) + '.').rstrip('0').split('.')[-1]) ``` Is there another, simpler way to do this?

Original source

Related problems