所以,问题:
如何在长度为 9 的字符串中“重新添加”所有前导零(从 Long 转换时会被截断)?
更多详情:
在“前端”(API)中,发送进来的String值长度为9,: 例如“000000000”、“000000001”、“000000010”
请求正文:
{
someObjects: [
someObject1: {
Id: “000000000”;
],
someObject2: {
Id: “000000001”
},
someObject3: {
Id: “000000010”
}
}
对应的java类是:
class SomeObject {
Long id;
}
在处理程序方法中:
public void someRequestHandlerMethod(List<SomeObject> someObjects) {
for(SomeObject someObject : someObjects) {
Long Id = someObject.getId();
LOGGER.info(“Id is: ”+Id);
}
}
发生的情况是,如果一个数字以零开头,当它转换为 Long 时,剩余数字前面的所有零都会被截断。 例如 “000000000”变为“0” “000000001”变为“1” “000000010”变为“10” 等等。
所以打印出来:
Id is: 0 (instead of Id is: 000000000).
Id is: 1 (instead of Id is: 000000001).
Id is: 10 (instead of Id is: 000000010).
问题:如何使用字符串操作保留零或“重新添加”它们,以便打印出来:
“000000000” is printed out as “000000000” and not as “0”
“000000001” is printed out as “000000001” and not as “1”
“000000010” is printed out as “000000010” and not as “10”.
基本上,保留或“重新添加”长度为 9 的数字字符串中的所有前导零?
任何帮助将不胜感激!
非常感谢!
基于 Ellioth Frisch 的评论并假设类
SomeObject
没有其他属性,请尝试以下操作:
public record SomeObject( long id )
{
@Override
public final String toString() { return "%09d".formatted( id ); }
}
你的循环将如下所示:
public final void someRequestHandlerMethod( final List<SomeObject> someObjects )
{
for( final var someObject : someObjects )
{
LOGGER.info( “Id is: %s”.formatted( someObject ) );
}
}