Im trying to count the numbers before and after a decimal place.
For example 1452.13 before would be 4 before and after would be 2.
The value is stored in a string i think i may need to use the len with find but cannot figure it out?
would appreciate any help.
There a loads of ways. eg here
This is quite a fast technique to find digits after the decimal point.
It can be copied and modified to find the places before the decimal point
Function CountDecimalPlaces(aNumber As Double) As Long
Dim len1 As Long, len2 As Long
len1 = Len(CStr(aNumber))
len2 = Len(CStr(Int(aNumber)))
CountDecimalPlaces = len1 - len2 + CLng(len1 <> len2)
End Function
Function CountInteger(aNumber As Double) As Long
CountInteger = Len(CStr(Int(aNumber)))
End Function
Neither of the above rely on you decimal character being a "."
Can I play too? :D
Num = 1452.13
Debug.Print Len(Split(Num, ".")(0)) '<~~ Length of number before decimal
Debug.Print Len(Split(Num, ".")(1)) '<~~ Length of number After decimal
EDIT:
I am assuming that you will pass only decimals. But to make it foolproof, you can use this
Num = 1452
Debug.Print Len(Split(Num, ".")(0)) '<~~ Length of number before decimal
If InStr(1, Num, ".") Then Debug.Print Len(Split(Num, ".")(1)) _
Else Debug.Print 0 '<~~ Length of number After decimal
Using an excel formula you would be best to use the following (fast) formulas
=LEN(INT(A1))
=LEN(A1) - IF(INT(A1)-A1,1,0) - LEN(INT(A1))
=LEN(LEFT(A1;LEN(A1)-FIND(".";A1))-1)
=LEN(RIGHT(A1;LEN(A1)-FIND(".";A1)))
That is, if your decimal character is a dot.
If you are working with Microsoft Word:
Sub dot()
Dim Num As Variant
Num = 1452.13
MsgBox "You number: " & Num
MsgBox "Length of number before decimal: " & Len(Split(Num, ".")(0))
MsgBox "Length of number After decimal: " & Len(Split(Num, ".")(1))
End Sub
Based on Siddharth Rout answer
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.