简体   繁体   English

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

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

Does anyone know how to convert an integer into a String value with specified number of digits in using Groovy script code? 有谁知道如何使用Groovy脚本代码将整数转换为具有指定位数的String值? For example, I want to convert the integer values 1, 2, 3, 4 to the 4-digit strings as "0001", "0002", "0003" and "0004". 例如,我想将整数值1、2、3、4转换为4位字符串,例如“ 0001”,“ 0002”,“ 0003”和“ 0004”。

Just use Java's String.format : 只需使用Java的 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 其他选项可以在这里找到

Use sprintf , which is added to the Object class so it is always available: 使用sprintf ,它已添加到Object类中,因此始终可用:

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

See the JDK documentation for the format string for more information. 有关更多信息,请参见JDK文档中的格式字符串

You can use String.format() like described in JN1525-Strings 您可以像JN1525-Strings中所述使用String.format()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM