简体   繁体   中英

Parse String to long with leading zero

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?

You cannot because a long does not have a leading zero. A long is supposed to store integers (the mathematical concept, not int ) , ie

数轴

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 eg java.util.Formatter .

Are you sure you even want to have a long/an integer? What do you want to do with it?

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

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

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.

You can tweak the code. First get the length of string.

String input  =   "0888880747";

System.out.println(String.format("%0"+input.length()+"d", Long.valueOf(input)))):

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.

如果您的值是 long,则左侧(前导)的任何零都没有数学价值,因此,在您进行解析时,它们会被剥离。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM