-1

Am trying to code a Java calculator. Am running into some NumberFormat exceptions when trying to compute the following:

99.9(4x/8+k)

The funny thing is that its giving me the error after I distribute 99.9 only if the product of 99.9 and "k" is greater than or equal to 1000. So, for values greater than 10. In my code I try to load a string variable with the sums of all the constants of an equation, it is then that the error occurs. Here's what the code looks like:

double constantSum = 0;
//create a stringtokenizer object and convert each token to a double as  
//follows, then, add the double to constantSum
constantSum = constantSum + Double.valueOf(token);//the token comes 
//from the stringtokenizer object 

The input that Double.valueOf(token) receives is 1098.900 which is the product of 99.9 and 11, notice that the input has been rounded to the thousandths place by a NumberFormat object I initialized in the code.

any ideas on how to get rid of this NumberFormat exception

Here are the details of how the exception looks like: Exception in thread "main" java.lang.NumberFormatException: For input string: "1,098.900" at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043) at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)

thanks

i_o
  • 777
  • 9
  • 25
  • You're wrong, the input is not `1098.900`, it is `1,098.900`. See error message. Why would you even have that intermediate value as a string in your code? – Andreas Jan 16 '17 at 04:47
  • Possible duplicate of [What is a NumberFormatException and how can I fix it?](http://stackoverflow.com/questions/39849984/what-is-a-numberformatexception-and-how-can-i-fix-it) – xenteros Jan 25 '17 at 06:45

2 Answers2

2

The exception is probably being caused by the comma which is inside the token string. For a quick fix, you can try stripping away all commas:

constantSum += Double.valueOf(token.replaceAll(",", ""));
                                               ^^^^ this removes all commas
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

You cant have the comma in the string you want to turn into a double. Remove the comma and it should work.

Michael Sharp
  • 496
  • 3
  • 10