There are several ways to add or remove leading zeroes.
I'll list some of them here.
| Command | Add or Remove | Advantage(s) | Disadvantage(s) |
|---|---|---|---|
SET /A Var = 100%Var% %% 100 |
Remove | Fail-safe for numbers up to and including 99, with or without leading zero | |
SET Var=10%Var% |
Remove | Fail-safe for numbers up to and including 99, with or without leading zero | Way too much code for just 2 digits |
IF "%Var:~0,1%"=="0" SET Var=%Var:~1% |
Remove | Fail-safe for numbers up to and including 99, with or without leading zero; just repeat the command once for every added digit | |
:Loop |
Remove | Fail-safe for any number, with or without leading zero | A lot of code; use only for larger numbers or in case the number of digits is unpredictable |
FOR /F "tokens=* delims=0" %%A IN ("%Var%") DO SET Var=%%A |
Remove | Fail-safe for any number, with or without leading zero; fast | |
IF %Var% LSS 10 SET Var=0%Var% |
Add | Works for numbers 0..9 (without leading zero), 00..07 (with leading zero), and 10..99 | Fails on 08 and 09 if %Var% does have a leading zero, because batch file math interprets numbers with leading zeroes as octal |
IF 1%Var% LSS 100 SET Var=0%Var% |
Add | Fail-safe for numbers up to and including 99, with or without leading zero | |
SET Var=0%Var% |
Add | Fail-safe for numbers up to and including 99, with or without leading zero; easily scaled up to any number of digits |
| Notes: | (1) | Modulo division method (first command in the table above) by Paul Ruggieri. |
| (2) | For large numbers (greater than 215 for Windows 2000 or 231 for XP and later) use the string based manipulations only, as integer math will fail on these large numbers. |
| visitors can't be wrong... | page last uploaded: 27 July 2010, 21:51 |