简体   繁体   English

如何获得小数位数

[英]How to get number of decimal places

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: 您可以使用正则表达式来解析value ,捕获十进制数字并计算匹配的长度(如果有):

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 else分割字符串要少一些“原始”,但不确定是否更简单或更易读。

You dont need regex, you can convert to float and convert back to string! 你不需要正则表达式,你可以转换为float并转换回字符串! this automatically will remove the zeroes : 这会自动删除零:

>>> def convertor(s):
...       try :
...          int(s.rstrip('0').rstrip('.'))
...          return 0
...       except: 
...          return len(str(float(s)).split('.')[-1])
... 
>>> convertor('4.0230')
3
>>> convertor('4.0')
0
>>> convertor('4')
0

you could also just try something like: 你也可以试试像:

try:
    return len(str(num).split('.')[1].rstrip('0'))
except
    return 0

By string process: 按字符串流程:

  1. Check . 检查. is present in number string or not. 是否存在数字字符串。
  2. If Not present then return 0. 如果不存在则返回0。
  3. If present the split number string by . 如果出现拆分号码字符串. and get second item from the split result. 并从拆分结果中获取第二项。
  4. Remove 0 from the right side. 从右侧删除0。
  5. Return len of item. 返回len项。

code: 码:

>>> def dCount(no_str):
...    if "." in no_str:
...         return len(no_str.split(".")[1].rstrip("0"))
...    else:
...         return 0
... 
>>> dCount("2")
0
>>> dCount("2.002")
3
>>> dCount("2.1230")
3
>>> dCount("2.01230")
4
>>> 
import re

def f(s):
    ls = s.split('.', 1)
    if len(ls) == 2 and re.match(r'\d*$', ls[1]):
        return len(ls[1].rstrip('0'))
    return 0

assert f('12') == 0
assert f('12.') == 0
assert f('12.1') == 1
assert f('12.100006') == 6
assert f('12.1.3') == 0
assert f('12.1abc') == 0
assert f('12.100000') == 1

The best and the most Pythonic way to achieve this is: 最好和最Pythonic的方法是:

import decimal
x = '56.001000'
x = x.rstrip('0')  # returns '56.001'
x = decimal.Decimal(x)  # returns Decimal('0.001')
x = x.as_tuple().exponent  # returns -3
x = abs(x)  #returns 3

Above code can be written in simpler way as: 上面的代码可以用更简单的方式编写:

>>> x = '56.001000'
>>> abs(decimal.Decimal(x.rstrip('0')).as_tuple().exponent)
3

Below is the list of used functions for more reference: 以下是使用函数列表以供参考:

  1. str.rstrip() : Return a copy of the string with trailing characters removed. str.rstrip() :返回删除了尾随字符的字符串副本。
  2. decimal.Decimal() : Construct a new Decimal object based from value. decimal.Decimal() :根据值构造一个新的Decimal对象。
  3. x.as_tuple(): Returns a namedtuple of the format: DecimalTuple(sign=0, digits=(1,), exponent=-3) x.as_tuple():返回一个namedtuple格式:DecimalTuple(标志= 0,位=(1,),指数= -3)
  4. abs() : Return the absolute value of a number. abs() :返回数字的绝对值。

You could try using the Decimal function in python: 您可以尝试在python中使用Decimal函数:

abs(Decimal(string_value).as_tuple().exponent)

as explained in Easy way of finding decimal places 如在查找小数位的简单方法中所解释的那样

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM