Search code examples
androidstring-formatting

Trying to write a the symbol '%' in strings.xml


I've tried all the possible variations I've found here on StackOverflow for writing a percent (%) symbol and I my app keeps crashing.

Here is what I want the text to look like:

50.0%
Complete.

Here is the string I am escaping in my strings.xml file:

<string name="work_package_percent_complete">%.1f%%\nComplete</string>

The error I am getting from the compiler is:

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.bechtel.pf.mock, PID: 8252 java.util.UnknownFormatConversionException: Conversion = ' '

Here's where I am calling String.format:

@JvmStatic
fun formatPercentageText(context: Context, percentage: Float): String {
    return String.format(
        context.resources.getString(
            R.string.work_package_percent_complete,
            percentage
            )
        )

}

It seems like it's not getting escaped properly.


Solution

  • It seems that there was no reason to do String.format() when just retrieving the string would automatically handle the formatting for me.

    So it just becomes:

    @JvmStatic
    fun formatPercentageText(context: Context, percentage: Float): String {
        return context.resources.getString(
                R.string.work_package_percent_complete,
                percentage
                )
    }