Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting String to Number in Java

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
like image 871
Lakshan Prabhu Avatar asked Jan 23 '17 18:01

Lakshan Prabhu


People also ask

How do I convert a string to a number?

The unary plus operator ( + ) will convert a string into a number. The operator will go before the operand. We can also use the unary plus operator ( + ) to convert a string into a floating point number. If the string value cannot be converted into a number then the result will be NaN .

Can I typecast string to int in Java?

We can convert String to an int in java using Integer.parseInt() method. To convert String into Integer, we can use Integer.valueOf() method which returns instance of Integer class.


1 Answers

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

 Number number = NumberFormat.getInstance().parse(string);
like image 79
minigeek Avatar answered Oct 29 '22 16:10

minigeek