Gil Zellner
Gil Zellner

Reputation: 979

In groovy, how do I return a zero padded range?

I need to return a value between 001-999. so naturally i can use ranges:

return 1..999

but I need to return something between 001 and 999, meaning to zero pad the single and double digit numbers. Is there an elegant way to do this in groovy ?

I can of course do this with a for loop, but there is probably a more elegant way to do this i couldn't find.

Upvotes: 2

Views: 1445

Answers (2)

dmahapatro
dmahapatro

Reputation: 50265

Easy solution would be:

(1..999).collect { String.format('%03d', it) }

Manipulate%03d to pad with whatever padding needed. For example:

`%04d` => 0001
`%05d` => 00001
...... so on and so forth

Upvotes: 4

Dmitry Khamitov
Dmitry Khamitov

Reputation: 3286

This can be a solution:

(1..999).collect {
    it.toString().padLeft(3, '0')
}

Or you may want your padding to be adjustable to the range:

def range = 1..999
def digitsNum = range.to.toString().length()
def padded = range.collect {
    it.toString().padLeft(digitsNum, '0')
}

Upvotes: 4

Related Questions