Ashish Agarwal
Ashish Agarwal

Reputation: 14925

java.lang.NumberFormatException for large numbers

In the code below, I am getting a java.lang.NumberFormatException when entering large numbers ~1000000000. The error occurs on the second-last line -\

int integer = Integer.parseInt(split[0]);

It should work in theory since Integer type supports till 2^32-1 but it doesn't

Scanner user_input = new Scanner(System.in);
//accept user input and convert into double
String s = user_input.next();
double number = Double.parseDouble(s);
System.out.println(number);

String answer = "";

//Split the entered number into Integer and Decimal parts
String split[] = Double.toString(number).split("\\.");
int integer = Integer.parseInt(split[0]);
int decimal = Integer.parseInt(split[1]);

Upvotes: 1

Views: 2840

Answers (4)

shazin
shazin

Reputation: 21883

Ofcourse the number 1000000000 is valid but I suspect the character ~ causes the NumberFormatException. You should be careful anyway with this code because a number like this 1.34184E24 is a valid Double in java but parsing the decimal split using Integer.parseInt will also result in NumberFormatException because there is an E.

Upvotes: 0

Matthew Farwell
Matthew Farwell

Reputation: 61705

The problem is probably because of the representation of a large double which will be in scientific notation:

1.0E9

This will mean that the split is failing, try printing out the value of the string you are parsing.

When you call toString on a double, the format used can vary, try using DecimalFormat instead:

new java.text.DecimalFormat("0.00000000").format(number)

Upvotes: 2

Dan D.
Dan D.

Reputation: 32391

The problem is that huge numbers are represented like 1.E9 or similar. So, when you do the split for getting the integer value you will get 1 and for the decimal part you will get E9 which is not a number.

Upvotes: 0

BeeOnRope
BeeOnRope

Reputation: 64905

Per the Javadoc, this occurs when "the string cannot be parsed as an integer". Among other reasons, this would be the case if the value exceeds Integer.MAX_VALUE or Integer.MIN_VALUE.

So things larger than about 2 billion or smaller than negative 2 billion (2^31-1, and -2^31 to be exact). Your example, -1,000,000,000 (commas added) should work.

Upvotes: 0

Related Questions