format statement in a string resource file
Inside file strings.xml
define a String resource like this:
<string name="string_to_format">Amount: %1$f for %2$d days%3$s</string>
Inside your code (assume it inherits from Context) simply do the following:
String formattedString = getString(R.string.string_to_format, floatVar, decimalVar, stringVar);
(In comparison to the answer from LocalPCGuy or Giovanny Farto M. the String.format method is not needed.)
You should add formatted="false"
to your string resource
Here is an example
In your strings.xml
:
<string name="all" formatted="false">Amount: %.2f%n for %d days</string>
In your code:
yourTextView.setText(String.format(getString(R.string.all), 3.12, 2));
You do not need to use formatted="false"
in your XML. You just need to use fully qualified string format markers - %[POSITION]$[TYPE]
(where [POSITION]
is the attribute position and [TYPE]
is the variable type), rather than the short versions, for example %s
or %d
.
Quote from Android Docs: String Formatting and Styling:
<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
In this example, the format string has two arguments:
%1$s
is a string and%2$d
is a decimal integer. You can format the string with arguments from your application like this:Resources res = getResources(); String text = res.getString(R.string.welcome_messages, username, mailCount);