[英]How do I find the length of a decimal number without counting the decimal point?
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?"如果我有一个数字 7.14285 并且我想找到其中的位数,我该怎么做而不将小数点也算作一个“数字”?
For example, I did this:例如,我这样做了:
n = 7.14285
digits = len(str(n))
print(digits)
But it returns "7" to me as the answer.但它向我返回“7”作为答案。
If I do:如果我做:
n = 714285
digits = len(str(n))
print(digits)
Then it returns "6" to me as the answer.然后它返回“6”给我作为答案。
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?那么,如何计算这个十进制数的位数并使其等于 6 而不是 7,同时保持 n = 7.14285?
.isdigit
will return True
if a given character is a digit.如果给定字符是数字, .isdigit
将返回True
。 True
also works like the integer 1
so you can sum it True
也像 integer 1
一样工作,所以你可以把它加起来
sum(d.isdigit() for d in str(n))
But be careful!不过要小心! 7.14285
is really a decimal approximation of a binary float. 7.14285
实际上是二进制浮点数的十进制近似值。 Given greater precision, its closer to 7.1428500000000001435296326235402375459671020507812500
.如果精度更高,它更接近7.1428500000000001435296326235402375459671020507812500
。 If this value n
started out as a string, keep it that way.如果这个值n
以字符串形式开始,请保持这种状态。 Otherwise keep in mind that str(some_float)
gives an approximation of the number.否则请记住str(some_float)
给出了数字的近似值。
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
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. str(n)
之后的.replace(".","")
) 将删除小数点。
If you are sure that you need length of floating number, then you can just subtract 1 from the length of given floating number.如果你确定你需要浮点数的长度,那么你可以从给定的浮点数的长度中减去 1。
len(str(n))-1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.