Home > OS >  How do I find the length of a decimal number without counting the decimal point?
How do I find the length of a decimal number without counting the decimal point?

Time:09-28

If I have a number 7.14285 and I wanted to find the number of digits in this, how do I do so without the decimal point also being counted as a "digit?"

For example, I did this:

n = 7.14285
digits = len(str(n))
print(digits)

But it returns "7" to me as the answer.

If I do:

n = 714285
digits = len(str(n))
print(digits)

Then it returns "6" to me as the answer.

So, how do I count the number of digits in this decimal number and make it equal 6 instead of 7 while keeping n = 7.14285?

CodePudding user response:

.isdigit will return True if a given character is a digit. True also works like the integer 1 so you can sum it

sum(d.isdigit() for d in str(n))

But be careful! 7.14285 is really a decimal approximation of a binary float. Given greater precision, its closer to 7.1428500000000001435296326235402375459671020507812500. If this value n started out as a string, keep it that way. Otherwise keep in mind that str(some_float) gives an approximation of the number.

CodePudding user response:

One way is just splitting the string using the point and counting the second element of the list that generates.

n = 7.14285
digits = str(n).split(".")
print(len(digits[1])) # The Output is 5

CodePudding user response:

We just have to remove that '.', Here we have the code to do so:

n = 7.14285
digits = len(str(n).replace(".",""))
print(digits)

The .replace(".","") after str(n) will remove the decimal point.

CodePudding user response:

If you are sure that you need length of floating number, then you can just subtract 1 from the length of given floating number.

len(str(n))-1
  • Related