将字符串解析为带有前导零的长整型字符串
长话短说(在Java中):
String input= "0888880747;
long convert = Long.parseLong(input);
convert的值现在是:888880747
如何将String
解析为long
但保留前导零?
Long story short (in Java):
String input= "0888880747;
long convert = Long.parseLong(input);
The value of convert is now: 888880747
How can I parse the String
to a long
but retain the leading zero?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不能,因为 long 没有前导零。 long 应该存储整数(数学概念,而不是
int
),即05
这样的字符串不是整数,5 是。您可以做的是在打印时格式化一个包含
5
并带有前导零的 long,请参见 java.util.Formatter。您确定您想要一个长整数/整数吗?你想用它做什么?
You cannot because a long does not have a leading zero. A long is supposed to store integers (the mathematical concept, not
int
), i.e.A string of characters like
05
is not an integer,5
is. What you can do is format a long that holds5
with a leading zero when you print it, see e.g. java.util.Formatter.Are you sure you even want to have a long/an integer? What do you want to do with it?
完成转换计算后,您必须将其更改回
String
,然后:You'll have to change it back to a
String
when you've done your calculations on convert, then:long
是一个数值。 000001 的数值与 1 没有什么不同:它是完全相同的数字。因此,一旦你有一个
long
,你就无法找出初始表示有多少个前导零。如果你真的关心这一点,那么你无论如何都不应该将输入处理为数字类型,而是存储
String
本身。A
long
is a numeric value. The numeric value of 000001 is no different from 1: It's the exact same number.So you can't find out how many leading zeroes the initial representation had, once you have a
long
.And if you really care about that, then you shouldn't handle the input as a numeric type anyway, but store the
String
itself, instead.如果您的值是长整型,则左侧(前导)的任何零都没有数学值,因此,当您进行解析时,它们会被删除。
If your value is a long, then any zeroes to the left (leading) have no mathematical value, therefore, they are stripped off when you do the parsing.
您可以调整代码。首先获取字符串的长度。
上面的 tweek 可以工作,但看起来不太好。如果前导零很重要,最好将值作为 String 读取并作为 varchar 而不是 Number 存储在数据库中。
You can tweak the code. First get the length of string.
The above tweek works but doesn't look good. Better to read the value as String and store in DB as varchar instead of Number if leading zeros matter.