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"

on
2,862 Views
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();
nf.setMaximumFractionDigits(2);
nf.setMinimumFractionDigits(2);
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.

Comment
Watch Question

## View Solution Only

Commented:
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

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

Commented:
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

Commented:
>  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):
http://www.trotek.ec-lyon.fr/~muller/cours/numeration/flp_ieee.html.en

Commented:

Commented:
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.