繁体   English   中英

获取小数位数的长度

[英]Get the length of decimal places

我有一张Excel工作表,其中有几列,其中一列是“ Amount ,在这里我必须验证每个单元格并检查小数点后的长度是否大于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 ),因此您可以检查字符串是否包含"." 之前,或者您可以检查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

它将数字转换为字符串,并使用"."分割"." 作为定界符,然后返回所返回数组中第二项的长度(它是"."之后的任何值)

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

暂无
暂无

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

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