简体   繁体   中英

Converting Double to String. Loses precision

I cannot convert double to string without losing precision.

Look

Double latitude = gps.getLatitude();
String latitude1 = Double.toString(latitude);
new onbuttonclickHttpPost().execute(latitude1);

Here is async class with rest. And in POST i send String and it is 3.0 which is not acceptable

    public class onbuttonclickHttpPost extends AsyncTask<String, Void, Void> {

    @Override
    protected Void doInBackground(String... f_url) {    

        byte[] result = null;
        String str = "";
       // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("_HERE_GO_MY_URL");

        try {

                // Add your data
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("lng", f_url[0]));
                nameValuePairs.add(new BasicNameValuePair("lat", "X"));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                // Execute HTTP Post Request
                HttpResponse response = httpclient.execute(httppost);
                StatusLine statusLine = response.getStatusLine();
                if(statusLine.getStatusCode() == HttpURLConnection.HTTP_OK){
                result = EntityUtils.toByteArray(response.getEntity());
                str = new String(result, "UTF-8");
            }
          } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }  

        return null;
    }

    /**
     * on getting result
     */
    protected void onPostExecute(String result) {
        // something with data retrieved from server in doInBackground
    }
}

String look like this 3.0 but should be 3.518972061574459

How convert with full precision ?

Edit: add little more code

The way you're doing it's right (you can see here that I get all the decimals: http://goo.gl/pORXg2 ). Maybe the problem is how you print it out.

try to convert double to String explicitly with format

String output=String.format("%.10f", 3.518972061574459);

and you'll got "3.5189720615" in output.

Is there any specific reason that you are not using

Double latitude = gps.getLatitude();
String latitude1 = latitude==null?"":latitude.toString()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM