Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

primitive types - 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...