Last Updated:

How to convert a string to a number in Java

Very often the next task is to convert a string to a numeric type. In Java, this can be done in many ways. The main thing is to take into account the maximum dimensionality of the data and accuracy (for fractional numbers).

Convert a string to an integer

 

To convert strings to integers, there are Integer.parseInt and Long.parseLong methods for converting to int and long types, respectively.

An easy way to get an int from a string is:

 

int a1 = Integer. parseInt("123");
System. out. println(a1);
 
 
Note: The Integer.parseInt method correctly converts the numbers in the int range (-2147483648..2147483647).

 

If a number exceeds these boundaries or contains invalid characters, a NumberFormatException will be thrown:

 

int a2 = Integer. parseInt("3000000000"); // NumberFormatException
int a3 = Integer. parseInt("123abc"); // NumberFormatException

If you need numbers larger than int, use the Long.parseLong method:

 

long b1 = Long. parseLong("3000000000");
System. out. println(b1);

For example, you can use such a utilitarian method, which, if it is impossible to correctly parse the string, will return zero:

 

public static long stringToLong(String s) {
try {
return Long. parseLong(s);
} catch (NumberFormatException e) {
return 0;
}
}

Convert a string to a fractional number

To convert strings to fractional numbers, you can use the Float.parseFloat and Double.parseDouble methods, which produce float and double numbers, respectively:

 

float f1 = Float. parseFloat("123.45");
System. out. println(f1);
double d1 = Double. parseDouble("123.45");
System. out. println(d1);

 

It is worth noting that it is better to use double instead of float because of the increased accuracy of double.

Convert large numbers

 

If you lack dimension to store long and double numbers, you can use BigInteger and BigDecimal:

System.out.println(new BigInteger("9223372036854775807000"));
System.out.println(new BigDecimal("9.223372036854776777E21"));

Here you will not be able to use the transformation to int because of the excess size of the int; will be converted to double, but with a loss of accuracy.

Conclusion

 

In this article, we described the standard methods for converting a string to a number. When choosing a method, you need to take into account the dimension of the types to which the number is given.