-2

In java the following code works:

double a = 15.5+0.5; 
System.out.println(a);

This will print 16.0.

So why does the following return a runtime error:

String a = "15.5+0.5";
Double b = Double.parseDouble(a);
System.out.println(b);

How can I get the second example to not give an error and behave like the first when converting the string to double and calculating a value?

Serverless chap
  • 183
  • 1
  • 9

1 Answers1

0

parseDouble, parseInteger etc. don't perform expression evaluation, they just perform conversions from the string representation of some value to the numeric representation (so "5.0" gets converted to 5.0).

See the documentation here for the precise definition of parseDouble's behaviour.


If you want to perform expression evaluation, you could look into Reverse Polish Notation and the Shunting Yard algorithm, or ideally a library designed for this. Alternatively, you can use a more "hacky" solution.

hnefatl
  • 5,860
  • 2
  • 27
  • 49