Myst
Myst

Reputation: 177

decimal format not working for output

i tried to format the data i retrieve from another page and so why does the output is not in the format. by right it should be 2236.29 but it shows 236.29482845736. i use this formatting at my first page and it works.

    //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");

this is my first page where i did the same thing but with no problems.

        //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");

the output is the same for distance and speed for the page with problem(first code) }

Upvotes: 1

Views: 1249

Answers (2)

Biraj Zalavadia
Biraj Zalavadia

Reputation: 28484

Try this way

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

Upvotes: 1

TheIT
TheIT

Reputation: 12219

Your problem is that you are calling df.format(...) but are ignoring the return value, which is the correctly formatted String representation of the decimal number.

For example, what you need to write is:

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

...

displayDistance.setText("Distance: " + valueString ...);

or simply

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

Upvotes: 0

Related Questions