Batch :RemLeadingZeros Function

AceInfinity

Emeritus, Contributor
Joined
Feb 21, 2012
Posts
1,728
Location
Canada
Here's a function I created in order to help prevent this fun error you get from numbers being interpreted indifferently.

Invalid number. Numeric constants are either decimal (17), hexadecimal (0x11), or octal (021).

This is commonly caused by leading zero's in a number. So here's my example use of the function i've created:

Code:
@echo off
setlocal enabledelayedexpansion

set n=000100
echo Original: %n%
call :RemLeadingZeros %n% n
echo After Call To RemLeadingZeros: %n%
echo.

pause && goto :eof

:RemLeadingZeros
set num=%1
set /a n=0

:tryagain
	set newnum=!num:~%n%!
	if not defined newnum ( set %2=0 && goto :eof )
	if %newnum:~0,1% neq 0 ( set %2=%newnum% && goto :eof )
	set /a n+=1
goto tryagain
 
Improved version:
Code:
@echo off
setlocal enabledelayedexpansion

set n=03058
call :RemLeadingZeros %n%
echo %n%

pause && goto :eof

:RemLeadingZeros
call :GetVarName %1
set param1=%1
set /a tmp1=0
:tryagain
	set newtmp1=!param1:~%tmp1%!
	if not defined newtmp1 ( set !vartmp!=0 && goto :eof )
	if %newtmp1:~0,1% neq 0 ( set !vartmp!=%newtmp1% && goto :eof )
	set /a tmp1+=1
goto tryagain

:GetVarName
for /f "tokens=1-2 delims==" %%G in ('set') do (
	if %%H equ %1 (
		set vartmp=%%G
	)
)
 

Has Sysnative Forums helped you? Please consider donating to help us support the site!

Back
Top