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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:01:18  来源:igfitidea点击:

Parse String to long with leading zero

javaparsinglong-integerzero

提问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 Stringto a longbut 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,即

number line

数轴

A string of characters like 05is not an integer, 5is. What you can do is format a long that holds 5with 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 Stringwhen you've done your calculations on convert, then:

String在完成转换计算后,您必须将其改回 a ,然后:

output = String.format("%06d", convert);

回答by Joachim Sauer

A longis 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 Stringitself, 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,则左侧(前导)的任何零都没有数学价值,因此,在您进行解析时,它们会被剥离。