Converting String to Number in Java

Lakshan Prabhu picture Lakshan Prabhu · Jan 23, 2017 · Viewed 25.7k times · Source

How can i convert a string to a abstract number, provided string is any valid number in java (say int, long, double etc).

I will not know the type of number in the string, so i can't use specific primitive parsing (like Integer.parseInt, Long.parseLong etc). Is there any generic way to convert it?

Eg:

  • String -> Number
  • "23423" -> 23423
  • "34.3" -> 34.3
  • "45364573747546" -> 45364573747546

Answer

minigeek picture minigeek · Jan 23, 2017

Use NumberFormat. Number cannot be instantiated because it is an abstract class.

 Number number = NumberFormat.getInstance().parse(string);