azzerty2017
azzerty2017

Reputation: 43

Invalid double when I try to convert string to double

I am actually trying to convert string data in double. I do not understand why I have always the error 'Invalid Double' when I try to do this :

double freq[]=new double[nb_points];
double pxx[]=new double[nb_points];
int nb_point=100;

 for (int i=0; i<bytes/2;i=i+15)
 {
    String strReceived_freq = new String(buffer,i, i+15);   
    freq[i]=Double.parseDouble(strReceived_freq);
    freq_value.setText(String.valueOf(freq[i]));
 }

Thanks for your help !

Upvotes: 0

Views: 107

Answers (2)

Kuldeep Rana
Kuldeep Rana

Reputation: 45

You should check value of String "strReceived_freq" may be it is "".

Minor suggestion instead of Doulbe.parseDoulbe() you should use

Double d = new Double(strReceived_freq);

Upvotes: 0

Ritt
Ritt

Reputation: 3349

There are many cases in which this error can occur. Example your string is "" (empty) or not properly parsed.

You need to catch the exception here.

Something like this..

double freq[]=new double[nb_points];
        double pxx[]=new double[nb_points];
        int nb_point=100;

        for (int i=0; i<bytes/2;i=i+15)
        {
            String strReceived_freq = new String(buffer,i, i+15);
            try {
                freq[i]=Double.parseDouble(strReceived_freq);
            }catch (NumberFormatException e){
                freq[i]=0;
            }

            freq[i]=Double.parseDouble(strReceived_freq);
            freq_value.setText(String.valueOf(freq[i]));
        }

Upvotes: 1

Related Questions