There are several techniques to add or remove leading zeroes.
I will list some of these here, all of them intended for unsigned decimal numbers.
To recognize line wrapping, command lines are interlaced with blank lines.
So in the following tables, you should treat command lines not separated by blank lines as a single command line.
Remove Leading Zeroes | |
---|---|
# | Command |
Pros and Cons | |
1 | SET /A Var = 100%Var% %% 100 |
|
|
2 | SET Var=10%Var% |
|
|
3 | IF "%Var:~0,1%"=="0" SET Var=%Var:~1% |
|
|
4 | :Loop |
|
|
5 | FOR /F "tokens=* delims=0" %%A IN ("%Var%") DO SET Var=%%A |
|
|
6 | FOR /F "tokens=* delims=0" %%A IN ("%Var%") DO SET /A Var=%%A+0 |
7 | FOR /F "tokens=* delims=0" %%A IN ("%Var%") DO SET Var=%%A |
|
|
8 | FOR /F "tokens=* delims=0" %%A IN ("%Var%") DO SET Var=%%A |
|
Of all techniques to remove leading zeroes presented here, #8 is the preferred one, as it will work for any number, without any restriction (5).
Note: | To remove leading zeroes from times' minutes and seconds, this clever technique by Andrew Dent may do the trick:SET TimeWithoutLeadingZeroes=%Time::0=:% This would fail only in the unlikely case that %Time% does not use leading zeroes in minutes and seconds (e,g. 2:0:12 would be set to 2::12 ).To remove leading zeroes from the hours will require additional code. |
Add Leading Zeroes | |
---|---|
# | Command |
Pros and Cons | |
1 | IF %Var% LSS 10 SET Var=0%Var% |
|
|
2 | IF 1%Var% LSS 100 SET Var=0%Var% |
|
|
3 | IF 1%Var% LSS 100 SET Var=0%Var% |
4 | SET Var=00%Var% |
|
Of all techniques to add leading zeroes presented here, #4 is the preferred one, as it will work for any number, without any restriction in length (5).
However, higher numbers will be truncated, e.g. if %Var%
equals 123 this technique returns 23.
See note 4 for a safer alternative using PowerShell or third party software.
Notes: | |
(1) | Modulo division method (first command in the first table) by Paul Ruggieri. |
(2) | Math based techniques can be used for numbers up to 9 digits for Windows XP and later, or up to 4 digits for Windows 2000. |
(3) | Math based techniques with "prefixes" can be used for numbers up to 5 digits for Windows XP and later, and only 1 or 2 digits for Windows 2000. |
(4) | My own ToString.exe can also be used to add leading zeroes, e.g. ToString.exe "{0:D3}" 5 will return 005 It will not truncate higher numbers, e.g. ToString.exe "{0:D2}" 123 will return 123 The same result with native code only can be achieved using powershell -c "'{0:D2}' -f %Var%" (or pwsh -c "'{0:D2}' -f %Var%" ) |
(5) | Actually, there is one restiction: the batch language's line length limit. However, unless you intend to use close to 900 digits, this won't be a problem. |
(6) | All of these commands are intended for decimal digits only, no signs allowed. |
page last modified: 2023-08-01; loaded in 0.0068 seconds