Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get number of decimal places

Tags:

python

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?

like image 757
David542 Avatar asked Mar 17 '23 22:03

David542


1 Answers

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.

like image 194
Stefano Sanfilippo Avatar answered Mar 29 '23 23:03

Stefano Sanfilippo