Android 十进制格式不适用于输出

Android 十进制格式不适用于输出,android,decimalformat,Android,Decimalformat,我试图格式化从另一个页面检索到的数据,为什么输出的格式不正确呢。右边应该是2236.29,但上面显示的是236.29482845736。我在我的第一页使用这种格式,它可以工作 //page with problem. long output DecimalFormat df = new DecimalFormat("#.##"); Bundle extras = getIntent().getExtras(); if (extras != null)

我试图格式化从另一个页面检索到的数据,为什么输出的格式不正确呢。右边应该是2236.29,但上面显示的是236.29482845736。我在我的第一页使用这种格式,它可以工作

    //page with problem. long output 
    DecimalFormat df = new DecimalFormat("#.##");
    Bundle extras = getIntent().getExtras();

    if (extras != null) 
    {
        Double value = extras.getDouble("dist");
        df.format(value);

        milesDistance = value * 0.000621371;
        df.format(milesDistance);

        Double durationValue = extras.getDouble("time");

        Double speedValue = extras.getDouble("velocity");
        Double mphSpeed = speedValue * 2.23694;
        df.format(speedValue);
        df.format(mphSpeed);

        displayDistance=(TextView)findViewById(R.id.finishDistance);
        displayDistance.setText("Distance: " + value + "meters " + milesDistance + "miles" + " Speed: " + speedValue + "m/s");
这是我的第一页,我做了同样的事情,但没有问题

        //page with no problem
        float[] results = new float[1]; 
        Location.distanceBetween(lat3, lon3, myLocation.getLatitude(), myLocation.getLongitude(), results);
        System.out.println("Distance is: " + results[0]);               

        dist += results[0];            
        DecimalFormat df = new DecimalFormat("#.##"); // adjust this as appropriate
        if(count==1)
        {
              distance.setText(df.format(dist) + "meters");
有问题的页面的距离和速度输出相同(第一个代码)
}您的问题是调用df.format(…),但忽略返回值,返回值是十进制数的正确格式字符串表示形式

例如,您需要编写的是:

Double value = extras.getDouble("dist");
String valueString = df.format(value);

...

displayDistance.setText("Distance: " + valueString ...);
或者干脆

displayDistance.setText("Distance: " + df.format(value) + "meters " + df.format(milesDistance) + "miles" + " Speed: " + df.format(speedValue) + "m/s");
这样试试

Double value = extras.getDouble("dist");
        System.out.println(String.format("%.2f",value));

你能解释一下外部字符串.format()的用途吗?干杯,我只是想确保我没有遗漏任何东西。虽然这个答案并没有回答他的问题,但它确实解决了他的问题,所以对你来说+1!