In my application, I get a number having leading zeros. I am trying to trim the leading zeros and get the actual number. I tried using /a
switch which considers right side of the assignment as an arithmetic expression. So I tried:
SET /a N = 00027
The above gave me the output of 23 which is the decimal equivalent of octal number 27. Then I found this solution online.
SET N = 00027 SET /a N = 1%N%-(11%N%-1%N%)/10
This seems working and is giving the output 27. Is there much easier way to trim the leading zeros in a batch file?
The simplest approach to solve the problem is to traverse the string up to the first non-zero character present in the string and store the remaining string starting from that index as the answer. If the entire string is traversed, it means all the characters in the string are '0'.
Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.
So %%k refers to the value of the 3rd token, which is what is returned.
The method you found is very good. It supports numbers up to 99,999,999 and is very fast.
There is a simpler way to use SET /A that works with numbers up to 9999. It uses the modulus operation. The method cannot be extended to larger numbers.
set n=0027 set /a n=10000%n% %% 10000
The FOR /F method that Dale posted works with "any" size number (up to 8191 digits). However, it needs just a bit more work to handle zero values.
set n=000000000000000000000000000000000000000000000000000027 for /f "tokens=* delims=0" %%N in ("%n%") do set "n=%%N" if not defined n set "n=0"
The exit command is pretty good at clearing leading zeros:
>set n=0000890 >cmd /c exit /b %n% >echo %errorlevel% 890
With this you can use number up to 32 bit integer limit and the piece of code is really small, despite additional call of cmd.exe could harm the performance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With