14

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".

3 Answers 3

22

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

Sign up to request clarification or add additional context in comments.

1 Comment

How to add localization settings for decimal punctuation?
8

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.

Comments

4

You can use String.format() like described in JN1525-Strings

values = [1, 2, 3, 4]
formatted = values.collect {
    String.format('%04d', it)
}
assert formatted == ['0001', '0002', '0003', '0004'] 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.