thenry thenry - 4 months ago 18
Android Question

Using %1$f but without trailing zeros

I have tried to search for a solution to this problem but I am unsure how to ask the question.

I am to populate a TextView with words and numbers and I have it set up in an Activity.

float leftTimeSecs = leftTime / 1000;
float roundedLeftSecs = round(leftTimeSecs, 3);
//How to access this directly from "strings" or .xml files
duration.setText(getString(R.string.time_data_sec, roundedLeftSecs,
getString(R.string.seconds)));


My string that I set the text to is:

<string name="time_data_sec">Duration: %1$f %2$s</string>


and the round function called is

public static float round(float value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bigDecimal = new BigDecimal(value);
bigDecimal = bigDecimal.setScale(places, RoundingMode.HALF_UP);
return bigDecimal.floatValue();
}


I want the output to print the value from roundedLeftSecs (which is leftTime rounded to three places) but when I don't hardcode the roundedLeftSecs in it will produce many trailing zeros after the rounded number.

I have found that %1$d is a decimal placeholder but it won't let me use that with a float or a double expression so I am unsure how to get rid of this zeros or if it is even possible.

Answer

For those who have the same issue ever, I solved it by using %1$s and converting my rounded number to a string and it works perfectly!

Here is where I wanted to round:

    float leftTimeSecs = leftTime / 1000;
                float roundedLeftSecs = round(leftTimeSecs, 3);
                String roundedLeftSecString = Float.toString(roundedLeftSecs);
                duration.setText(getString(R.string.time_data_sec, roundedLeftSecString,
                        getString(R.string.seconds)));

Here is the string:

<string name="time_data_sec">Duration: %1$s %2$s</string>
Comments