3

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?

3
  • 5
    That makes no sense at all. longs don't have leading zeros, only Strings do. Commented Oct 27, 2011 at 15:23
  • 00001 is the same as 1. Leading zeroes have no effect. Commented Oct 27, 2011 at 15:23
  • If you want leading zeros you need to store it in a String or format it to a string when printing out. Commented Oct 27, 2011 at 15:24

5 Answers 5

12

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.

number line

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?

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. I suspected as much, but I just wanted to make sure.
it means if it is written like 09 is considered as a string, not an integer and if you convert this into integer, it will give you only '9'.
6

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

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

Comments

2

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.

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.