-3

In my web service method, I have an input with type Long. I should add two zero in the left, so I converted it to String and I concat the two zero, then I should again converted to Long, I found that the Long type in java ignore left zero. How can I keep left zero in a Long value ?

Long a=58451236;
String b= "00"+String.valueOf(a);
Long c = Long.parseLong(b); // ==> Excepected value : 0058451236, found c= 58451236
mak_doni
  • 565
  • 1
  • 10
  • 29
  • 2
    Does this answer your question? [Parse String to long with leading zero](https://stackoverflow.com/questions/7918250/parse-string-to-long-with-leading-zero) – maloomeister Sep 22 '20 at 10:20
  • Use long as a number. To add leading zeroes on output, format the value: https://stackoverflow.com/questions/275711/add-leading-zeroes-to-number-in-java – Lesiak Sep 22 '20 at 10:22
  • The behavior you describe is expected and correct. Leading zeroes are generally meaningless on integer values. That is, 001 = 000001 = 1 = 01. They all have the same value and internally reduced to the bit representation. If you want to produce a String representation of that number such that it is padded with zeroes out to a specific number of digits then you can use various String formatting tools to do that. So the question becomes.. why does it matter to your system that there are no leading zeroes? – vsfDawg Sep 22 '20 at 10:28
  • You can use NumberFormat to format a number to have any amounts of digits that you want, which does include leading zeros. – NomadMaker Sep 22 '20 at 11:30

3 Answers3

4

You don't, a Long / long / Integer / int is a number, a number does not having leading zeros. Only a string representation of a number may have leading zeros.

If you absolutely need the leading zeros and the number 0001 is different from 001 then you are not dealing with numbers but just with strings that look like numbers and you should not convert it to a long in the first place.

luk2302
  • 55,258
  • 23
  • 97
  • 137
0

You cannot because a Long does not have a leading zero.

You can store it with String like this String.format("%02d", longValue);

divilipir
  • 882
  • 6
  • 17
  • `%02d` would ensure at least 2 decimal digits, but it seems that OP wants 10 digits, so `%010d` might be better. – kajacx Sep 22 '20 at 13:37
0

A long cannot have lead value as 0. I don't know about your use case but if you want to have 00 as lead don't convert it back to long, use String instead.

Jabir
  • 1
  • 1
  • 2