Java - Calculation Error
-
21-04-2021 - |
Question
I have wrote the following code to work out the difference between two floating point numbers to two decimal places:
double p = (Math.round((Double.parseDouble(a) - Double.parseDouble(a))*100))/100;
a
and b
are values in a String array that are numbers with decimal places, but obviously in the format of a String. I've tried to convert the String numbers into doubles and carry out the calculation with them but it doesn't seem to be working and throws this error:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "N/A"
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
Additional info: This uses data from the web and seemed to work before, but now it seems to have a bug of sorts. How can I solve this, and what's the problem?
Solution
The problem is that your String
variables a
and b
are not properly formatted - "N/A" is not a proper double
.
Please post how you are getting them.
OTHER TIPS
The root of your error is java.lang.NumberFormatException: For input string: "N/A"
That means a
or b
has a value of N/A.
There is no b in your code. If you are trying to do something like this:
String[] a = {"123","23"} ;
double p = (Math.round((Double.parseDouble(a[0]) - Double.parseDouble(a[1]))*100))/100;
System.out.println(p);
then you might have a typo mistake. Because it prints out fine for me.