1

I was trying to convert the String to int. However, its encounter error throw a NumberFormatException.

java.lang.NumberFormatException: For input string: "07221255201"

Code :

int value = Integer.valueOf(itemData.get(row).ERP_Customer_Item.trim());

Kindly advise.

2 Answers 2

3

7221255201 is out of primitive int range. You should use long type. This should work fine:

long value = Long.parseLong(itemData.get(row).ERP_Customer_Item.trim());

And for other contexts, try to have a practice of keeping primitive type ranges in mind when you write code. It is like having a hammer set consisting of hammers of different size and using the appropriate one in the context. For example, if you know that a particular variable will always be in the range of [-128,127] you should use short instead of int since you will waste a lot of bits in the latter case.

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

3 Comments

Hi , any sample can provide ? im newbie of this. THanks
@DamonNg added solution.
Long.valueOf returns a Long, if you just want a primative long, use Long.parseLong, else you're unboxing the object type.
1

Your number is larger than Integer.MAX_VALUE (2^31 - 1, or 2147483647), so it can't be parsed into an int.

Be careful converting from strings to numbers. Whatever created that number wasn't using java ints.

You can use a Long.parseLong to convert to a long, or Long.valueOf to get a Long (object instead of primative) in this case, but why are you converting from string in the first place? You're losing information (in this case the leading zeros which may or may not be important depending on what you do with the data). Conversion has a way of biting back somewhere down the line.

2 Comments

HI Mark , you are right , the leading zeros no longer working , any idea how to solve this ? @Mark Fisher
What are you doing with this ID and how is it failing to work? Are you handing it off somewhere else? Why do you need to convert it in the first place? Are you storing it somewhere that needs to be a number? Can you just use it in its raw string format as it has come to you? I suggest you have a deep think about how this value is being used and ask another more specific question if you are still having issues, maybe update your original question so we can help out. At the moment this is to broad to provide a solution.

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.