-1

I am trying to parse a String to Long which sometimes starts with 0. I want that the result maintains the "0" at the beginning of the Long (e.g. 0247484 instead of 247484).

I have tried this Long.parseLong(city.getId()) but it deletes the first "0".

Thank you

herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
Katherine99
  • 980
  • 4
  • 21
  • 40

3 Answers3

5

What you are asking for is not possible. In mathematical terms the leading 0 is absolutely meaningless so there is no way to represent it in a long.

What you probably want to do is control the rendering of the Long when you later print it out. There are all sorts of ways to control the formatting of a number, this may help: http://docs.oracle.com/javase/7/docs/api/java/text/NumberFormat.html

Tim B
  • 40,716
  • 16
  • 83
  • 128
3

You should use the DecimalFormat class: http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html

String number = "0247484";

long parsed = Long.parseLong(number);
System.out.println("Unformatted: " + parsed);

DecimalFormat df = new DecimalFormat("0000000");
String formatted = df.format(parsed);

System.out.println("Formatted: " + formatted);
Kevin Workman
  • 41,537
  • 9
  • 68
  • 107
1

Well, if you really need, you can do sth like that:

for example : 08530(string) to long ==> 8530 when you need to convert another time String, you can do :

String.format("%05d", number);

but you need to define a pattern. I hope it helps.

ZaoTaoBao
  • 2,567
  • 2
  • 20
  • 28