Parse String to long with leading zero

被刻印的时光 ゝ 提交于 2019-11-28 05:28:39

问题


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?


回答1:


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 holds 5 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?




回答2:


You'll have to change it back to a String when you've done your calculations on convert, then:

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



回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/7918250/parse-string-to-long-with-leading-zero

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!