18

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
5
  • 1
    You can just use Double.parseDouble(). This will work for all of the above examples. Commented Jan 23, 2017 at 18:52
  • Use Number class ? Commented Jan 23, 2017 at 18:52
  • Number class is abstract. So was not able to use it. NumberFormat / DecimalFormat does the job. Thanks. Commented Jan 23, 2017 at 19:20
  • See this solution for "Convert String to double in Java". Commented Sep 19 at 11:21
  • Related: Parse String into Number Commented Sep 19 at 11:22

9 Answers 9

22

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

 Number number = NumberFormat.getInstance().parse(string);
Sign up to request clarification or add additional context in comments.

4 Comments

And also NumberFormat can be substituted as e.g. DecimalFormat, but right, NumberFormat is good option
Only drawback of this approach is that it will also parse obvious text strings to numbers as long as they start with a number. i.e. "1.Textfield" will be parsed to 1 without exception.
For "1.123 / 4" it returns 1.123
Caution: NumberFormat.getInstance Returns a general-purpose number format for the current default FORMAT locale. Be aware of that if you don't want to parse 2.000 as either 2 or 2000 depending on locale - you should specify a locale that matches the expected format of your input.
2

Two cases:

  1. If you input string is less than 8 Bytes:

double primitiveNumber = Double.parseDouble(input);

  1. If Your input string is more than 8 bytes: you anyway cannot store it in a primitive, Then you can go with Number class, but this is not likely to happen since you expect a primitive.

Comments

1

Double will make your value lose precision if too long.

You should use a BigDecimal instead:

BigDecimal number = new BigDecimal("43.256");

You can then get different primitives like this:

try {
  int intValue = number.intValueExact();
} catch (ArithmeticException e) {
  try {
    long longValue = number.longValueExact();
  } catch (ArithmeticException e) {
    double doubleValue = number.doubleValue();
  }
}

Comments

0

Double.valueOf() will do fine unless you have a very long number.

2 Comments

valueOf() returns a Double, not a primitive.
@Code-Apprentice OP says he cannot use primitive-specific methods, and he asks for a generic way. Generic can't be primitive, otherwise being specific would be a must (while the OP wants a generic method).
0

The quickest way to do this is just always use Double.parseDouble(). If you need a general-purpose parser that determines which primitive to use, rather than always using the same type, then you will need to write your own. One way to do this is to use each parseXxx() method and lot of try...catch statements.

Comments

0

For integers:

int myInteger = Integer.parseInt("23423");

For doubles:

double myDouble = Double.parseDouble("34.3");

Comments

0

As long as your strings could be big numbers (suppose that no longer than primitive long and double), then generic way could be decide whether it is long or double.

Number n = Double.valueOf(string);
if((double)n.intValue() == n.doubleValue()){
   //n is double use n.doubleValue() or just use the n for generic purposes
}
else{
   //n is int use n.intValue() or just use the n for generic purposes
}

Comments

0

I do prefer BigDecimal only. Because it won't have the issues with size and precision

Comments

0

You can use Double.parseDouble() to convert your string to double. This will work even if the string is an integer:

String myString = "1234.56";
double myDouble = Double.parseDouble(myString);

If you need to check if it is an integer or a double:

String myString = "1234.56";
int myInt;
double myDouble = Double.parseDouble(myString);
if ((myDouble % 1) == 0) {
   myInt = (int) myDouble;
   System.out.println("myString is an integer: " + myInt );       
} else {
   System.out.println("myString is a double: " + myDouble );    
}

Or you can use Guava's DoubleMath.isMathematicalInteger():

String myString = "1234.56";
int myInt;
double myDouble = Double.parseDouble(myString);
if (DoubleMath.isMathematicalInteger(myDouble)) {
   myInt = (int) myDouble;
   System.out.println("myString is an integer: " + myInt );       
} else {
   System.out.println("myString is a double: " + myDouble );    
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.