英文:
How to convert String to Long without losing leading zero
问题
在我的网络服务方法中,我有一个类型为Long
的输入。我应该在左边添加两个零,所以我将其转换为String
,然后我连接这两个零,然后我应再次转换为Long
。我发现在Java中,Long
类型会忽略左边的零。如何在Long
值中保留左边的零?
Long a = 58451236;
String b = "00" + String.valueOf(a);
Long c = Long.parseLong(b); // ==> 期望值:0058451236,但实际 c = 58451236
英文:
In my web service method, I have an input with type Long
. I should add two zero in the left, so I converted it to String
and I concat the two zero, then I should again converted to Long, I found that the Long type in java ignore left zero. How can I keep left zero in a Long value ?
Long a=58451236;
String b= "00"+String.valueOf(a);
Long c = Long.parseLong(b); // ==> Excepected value : 0058451236, found c= 58451236
答案1
得分: 4
你不需要,在Long
/ long
/ Integer
/ int
中,它们是数字,数字没有前导零。只有数字的字符串表示可能有前导零。
如果你绝对需要前导零,并且数字 0001 与 001 不同,那么你处理的不是数字,而只是像数字一样的字符串,你最初就不应该将其转换为长整型。
英文:
You don't, a Long
/ long
/ Integer
/ int
is a number, a number does not having leading zeros. Only a string representation of a number may have leading zeros.
If you absolutely need the leading zeros and the number 0001 is different from 001 then you are not dealing with numbers but just with strings that look like numbers and you should not convert it to a long in the first place.
答案2
得分: 0
因为 Long
类型不允许以零开头,所以你不能这样做。
你可以使用 String
类型来存储,类似这样的方式:String.format("%02d", longValue);
英文:
You cannot because a Long
does not have a leading zero.
You can store it with String
like this String.format("%02d", longValue);
答案3
得分: 0
一个 长整型 不能以 0 作为前导值。我不清楚你的用例,但如果你想要以 00 作为前导,请不要将其转换回 长整型,而是使用 字符串。
英文:
A long cannot have lead value as 0. I don't know about your use case but if you want to have 00 as lead don't convert it back to long, use String instead.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论