Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an integer into a String value with specified length using Groovy script

Tags:

string

int

groovy

Does anyone know how to convert an integer into a String value with specified number of digits in using Groovy script code? For example, I want to convert the integer values 1, 2, 3, 4 to the 4-digit strings as "0001", "0002", "0003" and "0004".

like image 777
Spazik Avatar asked Jul 18 '12 15:07

Spazik


2 Answers

Just use Java's String.format:

def vals = [ 1, 2, 3, 4 ]

def strs = vals.collect {
  String.format( "%04d", it )
}

strs.each { println it }

prints:

0001
0002
0003
0004

Other options can be found here

like image 58
tim_yates Avatar answered Sep 25 '22 09:09

tim_yates


Use sprintf, which is added to the Object class so it is always available:

assert sprintf("%04d", 1) == "0001"

See the JDK documentation for the format string for more information.

like image 39
astimony Avatar answered Sep 24 '22 09:09

astimony