Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

how to remove leading zeroes from a string

Writer 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

0

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

5

This 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.

1

Use 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 Function

or

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy