获取小数位的长度
我有一个Excel工作表,其中有几列,一列是Amount
,我要validation每个单元格,并检查它的长度小数点后是否大于2,如果是的话,则抛出错误。
Public Function CheckLength(value As String) As Integer Dim n As Double Dim itg As Integer Dim dcm As Double n = value 'Say Value is 50.01 here itg = Int(n) 'Will be 50 dcm = Split(n - itg, ".")(1) 'But n-itg will yield something and dcm`s value will be '1000001 some strange value where as it has to be `01` or say whatever comes after decimal part CheckLength = Len(dcm) End Function
你可以这样做:
Public Function CheckLength(value As String) As Integer Dim n As Double Dim itg As Integer Dim dcm As Double n = value itg = Int(n) dcm = Len(CStr(n)) - InStr(CStr(n), ".") CheckLength = dcm End Function
注意:如果没有"."
在n中,它将返回总长度(因为它将是Len(CStr(n)) - 0
),因此您可以检查该string是否包含"."
之前,或者可以检查dcm
是否与Len(CStr(n))
,然后返回0
。
如果你真的检查数字,那么这将工作:
Function CheckLength(value As Double) As Integer If InStr(CStr(value), ".") Then CheckLength = Len(Split(CStr(value), ".")(1)) Else CheckLength = 0 End If End Function
它将数字转换为一个string,使用"."
分割"."
作为分隔符,然后返回返回数组中第二项的长度(即"."
之后的任何内容)
Const myNumber As Double = 50.13245 Debug.Print CheckLength(myNumber) '// Returns 5 '// Split 50.13245 on "." returns an array with 2 parts: '// (0) = "50" '// (1) = "13245" '// Length of (1) '13245' = 5