简体   繁体   English

将字符串解析为带前导零的 long

[英]Parse String to long with leading zero

Long story short (in Java):长话短说(Java):

String input= "0888880747;

long convert = Long.parseLong(input);

The value of convert is now: 888880747 convert 的值现在是:888880747

How can I parse the String to a long but retain the leading zero?如何将String解析为long但保留前导零?

You cannot because a long does not have a leading zero.你不能,因为 long 没有前导零。 A long is supposed to store integers (the mathematical concept, not int ) , ie long 应该存储整数(数学概念,而不是int ,即

数轴

A string of characters like 05 is not an integer, 5 is.05这样的字符串不是整数, 5是。 What you can do is format a long that holds 5 with a leading zero when you print it, see eg java.util.Formatter .长期保存你可以做的是格式5具有前导零,当你打印出来,例如参见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. long是一个数值。 The numeric value of 000001 is no different from 1: It's the exact same number. 000001 的数值与 1 没有区别:它是完全相同的数字。

So you can't find out how many leading zeroes the initial representation had, once you have a long .所以一旦你有一个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.如果您真的关心这一点,那么无论如何您都不应该将输入作为数字类型处理,而是存储String本身。

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.上面的 tweek 有效,但看起来不太好。 Better to read the value as String and store in DB as varchar instead of Number if leading zeros matter.如果前导零很重要,最好将值读取为 String 并作为 varchar 而不是 Number 存储在 DB 中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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