peet
peet

Reputation: 274

batch: split a number from var and fill up length if shorter than 3 chars

I read out a var which can go from "1" to "999999".

It represents a directory structure which is build in 3 digit names. so they start with "001" and end with "999" in both levels.

One method could be to take the var and, if it is shorter than 6 digits to fill it up and then take the first three and return them in a new var.

If the returned value is:       1 -> it represents:  000001 and i need: 000
If the returned value is:     999 -> it represents:  000999 and i need: 000
If the returned value is:    3999 -> it represents:  003999 and i need: 003
If the returned value is:   99999 -> it represents:  099999 and i need: 099
If the returned value is:  999999 -> it represents:  999999 and i need: 999

I'd really appreciate some code for this to handle it in a save and smart way.

Upvotes: 0

Views: 91

Answers (2)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200293

Prepend the variable with 5 zeroes, then extract the first 3 of the last 6 digits:

C:\>set "a=3999"
C:\>set "b=00000%a%"
C:\>set "c=%b:~-6,3%"
C:\>echo %c%
003

Upvotes: 2

peet
peet

Reputation: 274

depending on ansgars idea:

set "a=3999"
set "b=00000%a%"
set "c=%b:~-6%"
set "d=%c:~0,3%"
echo %d%

would work -while it does not look like very elegant coding. any better way someone?

Upvotes: 1

Related Questions