Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer.parseInt(String str) java.lang.NumberFormatException: Errors

I keep getting number format expectations, even though I'm trimming the strings and they don't contain non numerical characters bizarrely it works for some numbers and not others. Below is an example of a string I get number format exception for. Also, any string starting with 0 e.g "0208405223", is returned 208405223, there's no zero anymore is that supposed to happen?

String n="3020857508";
Integer a = Integer.parseInt(n.trim());
System.out.println(a);

This is the exception:

Exception in thread "main" java.lang.NumberFormatException: For input string: "3020857508"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:583)
    at java.lang.Integer.parseInt(Integer.java:615)
    at JavaBeans.Main.main(Main.java:15)
like image 209
manic bubble Avatar asked Dec 01 '22 14:12

manic bubble


1 Answers

The largest number parseable as an int is 2147483647 (231-1), and the largest long is 9223372036854775807 (263-1), only about twice as long.

To parse arbitrarily long numbers, use:

import java.math.BigInteger;

BigInteger number = new BigInteger(str);
like image 128
Bohemian Avatar answered Dec 04 '22 04:12

Bohemian