We help IT Professionals succeed at work.

Converting String input to double using NumberFormat. Got error: java.lang.NumberFormatException: For input string: "154,216.48"

marzbuzz asked
Last Modified: 2012-06-27
Hi I've got a input string ("154,216.48")  with: "," as separator which I should convert to a double

  public double calculateNAV()
    double NAV=calculateMarketCap()/calculateTotalShares();
    double NAVFormmated;
    NumberFormat nf = NumberFormat.getNumberInstance();
    String formattedNAV = nf.format(NAV);
    NAVFormmated=Double.parseDouble(formattedNAV); //error!
    return NAVFormmated;

java.lang.NumberFormatException: For input string: "154,216.48"
so, how can I convert this value to a double?
I know DecimalFormat with pattern should be able to fix it. But is that the best way to do it.

Indeed what I need is to convert a 12345.6789 to 12345.68. What's the best way to do it? Thanks.

Watch Question

You can not reliably contain a value with 2 decimals in a double.  In the double the decimals are stored in binary format so the only decimals that van be stored precicely are those that you may get by dividing by 2.  1/2, 1/4, 1/8, 7/8.

Actually we have the same problem in the decimal system. The only presice fractions we can write are those that come from dividing by 2 or 5. any other fraction will require rounding to limit the number of decimals. 1/3 becomes 0.333333333333..., etc.

You desire for 2 digits suggest you are working with money. the easiest solution is to store them in a long (as cents) that way all calculations will be correct. Later when you write the number for people to read you write them as dollars (with 2 decimals) again.

regards JakobA


Sounds interesting. But this is part of a homework. So I think it should be fine to lose some precision.
Unlock this solution and get a sample of our free trial.
(No credit card required)


Thanks orangehead911. I guess you are right. Using NumberFormat is a wrong choice. Just not that familiar with DecimalFormat. I guess DecimalFormat class is the best way to deal with this kind of question.
Top Expert 2006

>  In the double the decimals are stored in binary format.
It's much more complicated than that.
Doubles in java follow the IEEE 754 standard (composed of sign, exponent and mantissa):
Glad I could help! :-)
i want to convert string st="jan" to duoble

if i do Double.parseDouble(st);  // i am getting Numberformat exception
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.