how to remove leading zeroes from a string
Sebastian Wright
I have to extract the integer value from a string.
Its actually an amount field.
Say string can be 000000000000512 or 0000040000000
I want only the integer value from this string i.e.; 512/ 40000000
Please help with this in VB scripting
8 Answers
CInt("000000000000512")See conversion functions:
Use Clng if you expect to have large numbers, as already pointed out in a comment:
Clng("000000004000512")otherwise you'll have an overflow, as variant's subtype int is 16 bit in vbscript
5This will work even with a crazy long number
Function RemoveLeadingZeroes(ByVal str)
Dim tempStr
tempStr = str
While Left(tempStr,1) = "0" AND tempStr <> "" tempStr = Right(tempStr,Len(tempStr)-1)
Wend
RemoveLeadingZeroes = tempStr
End Function
strNewFileName = RemoveLeadingZeroes("0009283479283749823749872392384") I've used this technique before:
- replace the zeros with spaces
- left trim
- replace the spaces with zeros
Replace(LTrim(Replace(str, "0", " ")), " ", "0")
Note, this doesn't work if str has meaningful spaces in it.
1Use the Absolute Value of the number.
Var = ABS(Var) 2 Function TrimLeadingZeros(value) TrimLeadingZeros = value while left(TrimLeadingZeros, 1) = "0" and TrimLeadingZeros <> "0" TrimLeadingZeros = mid(TrimLeadingZeros, 2) wend
End Functionor
Function TrimLeadingZeros(value) dim i i = 1 while i < len(value) and mid(value,i,1) = "0" i = i + 1 wend TrimLeadingZeros = mid(value, i)
End Function Using regex:
Regex.Replace("000000000000512", "^0+", "") ' returns "512"
Regex.Replace("0000040000000", "^0+", "") ' returns "40000000" In case your string includes digits and characters, use a Do While statement:
string = "00000456ABC"
Do While Left(string, 1) = "0" string = Right(string, (Len(string)-1))
Loop Function TrimLZ(str) If Left(str, 1) = "0" Then TrimLZ = TrimLZ(Mid(str, 2, Len(str))) Else TrimLZ = str End If
End Function