Remove leading zeros in batch file

百般思念 提交于 2019-11-27 22:01:03

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"

You can use FOR /F to remove leading zeros.

C:\>SET n=00030
echo off
for /f "tokens=* delims=0" %a in ("%n%") DO echo %a
30

As you can see, the delims is set to 0. This will makes 0 as a delimiter. At the same time with tokens of * this will ensure that the leading 0's will be removed while the rest of the line will be processed (including trailing 0's).

You may refer to this link for more information about removal of leading 0's.

P.S. Do remember to use %%a instead of %a when you are running on batch file in FOR /F.

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 it's only a matter of removing all zeros, you can do it like this:

> SET n=00000002304650620000.23094400
> SET n=%n:0=%
2346562.23944
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!