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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With