如何使用Groovy脚本将整数转换为具有指定长度的String值

Spa*_*zik 13 string int groovy

有没有人知道如何使用Groovy脚本代码将整数转换为具有指定位数的字符串值?例如,我想将整数值1,2,3,4转换为4位数字符串为"0001","0002","0003"和"0004".

tim*_*tes 19

只需使用Java String.format:

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

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

strs.each { println it }
Run Code Online (Sandbox Code Playgroud)

打印:

0001
0002
0003
0004
Run Code Online (Sandbox Code Playgroud)

其他选项可以在这里找到


小智 6

使用sprintf,添加到Object类,以便始终可用:

assert sprintf("%04d", 1) == "0001"
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅JDK文档以获取格式字符串.