java 使用前导零将字符串解析为 long
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7918250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parse String to long with leading zero
提问by Tony
Long story short (in Java):
长话短说(Java):
String input= "0888880747;
long convert = Long.parseLong(input);
The value of convert is now: 888880747
转换的值现在是:888880747
How can I parse the String
to a long
but retain the leading zero?
如何String
将 a解析为 along
但保留前导零?
回答by middus
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.
你不能,因为 long 没有前导零。一个 long 应该存储整数(数学概念,不是int
),即
A string of characters like 05
is not an integer, 5
is. What you can do is format a long that holds 5
with a leading zero when you print it, see e.g. java.util.Formatter.
一串字符像05
不是整数,5
是。您可以做的是5
在打印时格式化带有前导零的 long ,参见例如java.util.Formatter。
Are you sure you even want to have a long/an integer? What do you want to do with it?
你确定你甚至想要一个长/整数吗?你想用它做什么?
回答by JonnyKash
You'll have to change it back to a String
when you've done your calculations on convert, then:
String
在完成转换计算后,您必须将其改回 a ,然后:
output = String.format("%06d", convert);
回答by Joachim Sauer
A long
is a numeric value. The numeric value of 000001 is no different from 1: It's the exact same number.
Along
是一个数值。000001 的数值与 1 没有区别:它是完全相同的数字。
So you can'tfind out how many leading zeroes the initial representation had, once you have a long
.
所以,你不能找出多少前导零初始表示过,一旦你有一个long
。
And ifyou really care about that, then you shouldn't handle the input as a numeric type anyway, but store the String
itself, instead.
而且,如果你真的关心这一点,那么你不应该处理输入的数字类型无论如何,但存储String
本身,而不是。
回答by pcalcao
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.
如果您的值是 long,则左侧(前导)的任何零都没有数学价值,因此,在您进行解析时,它们会被剥离。