Reputation: 45
I am creating a function that takes a number and prints the number of digits in the number. I have it working for ints but I want it to work for floats, too. I know it's simple but I am a beginner. I tried using int(float(num))
but that produced an error (ValueError: could not convert string to float: '-f'
). I also tried using .replace
but that didn't work. Any hints? Thank you
import sys
def digits(num):
count = len(num)
return count
num = sys.argv[1]
count = digits(num)
print(digits(num))
Upvotes: 1
Views: 2769
Reputation: 326
If you just want to count how many values are in the number you can modify your code as follows (only for positive floats and integers)
count = len(num.replace('.', ''))
To work around with negative values you can use json
module. It will cover you mantisa case.
import json
def count_digits(num):
num = json.loads(num) # returns type bound value
digit_str = str(abs(num)).replace('.', '')
return len(digit_str)
Try:
my_float = '1e+30'
actual_float = json.loads(my_float)
print(type(actual_float)) # returns <class 'float'>
Notice: json.loads works only with string objects, so you're good to go with applying this function to your arguments as they are strings by default.
You can also use re
module (regular expressions):
import re
def count_digits(num):
return len(re.sub(fr'[.+-]', '', num))
Here you use re.sub to substitute .
, +
, and -
sign for nothing and return the length of the resulting string.
Notice: with re
module you're working with strings!
The last approach I can come up with is by using eval
function
eval('-1e+15')
Upvotes: 1
Reputation: 11
Your function is not working with int nor float it is all strings
So i would say you should subtract 1 to the count if there is a decimal point
Try this:
def digits(num):
count = len(num) if '.' not in num else len(num) - 1
return count
Upvotes: 0
Reputation: 9836
Try this function
def getDigitCount(input):
s=str(abs(input))
t=-1 if "." in s else 0
return len(s) + t
Use it as follows
getDigitCount(2312.5262627)
which yields to 11
. Notice, that this works for negative floats as well.
getDigitCount(-2312.5262627)
which also yields to 11
as desired.
Upvotes: 0