Double parameter with 2 digits after dot in strings.xml? - android

I want to have a parameter in one string in strings.xml and this parameter should be a double value. So I use %1$f. Here - http://developer.android.com/reference/java/util/Formatter.html there are many examples, but what if I want to have have a few double/float parameters and I want only the second one to have 2 digits after .? I tried to use combinations like %2$.2f or %2.2$f. Nor of them worked. %.1f does not work as well.
So, does anybody know how can I "customize" a float/double value inside a strings.xml? Thanks.

Just adding to #David Airam's answer here; the "incorrect" solution he gives is actually correct, but with a bit of tweaking. The XML file should contain:
<string name="resource1">Hello string: %1$s, and hello float: %2$.2f.</string>
Now in the Java code:
String svalue = "test";
float sfloat= 3.1415926;
String sresult = getString(R.string.resource1, svalue, sfloat);
The exception that #David Airam reported is from trying to jam a String into a format specifier with %f, which requires a floating point type. Use float and there is no such exception.
Also, you can use Float.valueOf() to convert a String to a float in case your input data was originally a string (say, from a EditText or something). However, you should always try/catch valueOf() operations and handle the NumberFormatException case, since this exception is unchecked.

%.1f work for me if you like to show only 1 digit after ','

Define is strings.xml file
<string name="price_format">$%,.2f</string>
//For using in databinding where amount is double type
android:text="#{#string/price_format(model.amount)}"
//For using in java runtime where priceOfModifier is double type
amountEt.setText(context.getResources().getString(R.string.price_format, priceOfModifier));

This worked for me.
<string name="market_price">Range ₹%1$.0f - ₹%2$.0f</string>
android:text="#{#string/market_price(viewModel.suggestedPriceRange.max, viewModel.suggestedPriceRange.min)}"
Outputs: Range ₹500 - ₹1000
In ₹%1$.0f, .0f defines how many digits you want after the decimal.

A simpler approach:
<string name="decimalunit">%.2f%n</string>
float sfloat= 3.1475926;
String sresult = getString(R.string.decimalunit, sfloat);
Output: 3.15

If it were me I'd store the values in the resources as simple values, and then use formatter methods to control how they're displayed, roughly like this
public String formatFigureTwoPlaces(float value) {
DecimalFormat myFormatter = new DecimalFormat("##0.00");
return myFormatter.format(value);
}
public String formatFigureOnePlace(float value) {
DecimalFormat myFormatter = new DecimalFormat("##0.0");
return myFormatter.format(value);
}

I now that this reply is arriving too late... but I hope to be able to help other people:
Android sucks with multiple parameters substitutions when you want decimal numbers and format this in common style %a.bf
The best solution I have found (and only for these kind of resources) is put the decimal parameters as strings %n$s and in the code apply my conversion with String.format(...)
Example:
INCORRECT WAY:
// In xml file:
<string name="resource1">You has a desviation of %1$s and that is a %2$.2f%% percentage.</string>
// And in java file
String sresult = getString(R.string.resource1, svalue, spercentage); // <-- exception!
This solution is technically correct but incorrect due to android substitution resources system so the last line will generate an exception.
CORRECT WAY / SOLUTION:
Simply convert the second parameter into a String.
<string name="resource1">You has a desviation of %1$s and that is a %2$s percentage.</string>
And now in the code:
...
// This is the auxiliar line added to solve the problem
String spercentage = String.format("%.2f%%",percentage);
// This is the common code where we use the last variable.
String sresult = getString(R.string.resource1, svalue, spercentage);

Related

Android Kotlin Do not concatenate test displayed with setText. Use resource string with placeholders

And also "String literal in setText cannot be translated "
Now there are posts on this, but nothing seems working for me. Or need a proper explanation.
How to use string resources
Getting warning on this
pTxt.text = "Total : $ $price"
Here, price is a value
if use this
pTxt.setText(R.string.displayPriceMsg, price)
it gives an error.
tried String.format() but giving garbage value.
Have this in strings.xml
<string name="displayPriceMsg">Total : $ %1$d</string>
You have to pass format arguments to the getString method:
pTxt.text = context.getString(R.string.displayPriceMsg, price)

How to use Android xliff:g

Can someone please explain the xliff:g for strings/localization.
I understand that xliff:g is not supposed to translate anything inside the <> things, but I'm confused how exactly I'd use this in code.
An example I have in my case is the practice spanish translations that I have has:
<string name="order_quantity">Cantidad: <xliff:g id="quantity" example="2">%d/xliff:g</string>
I am now trying to get localized strings with xliff:g to work.
What is id here and what does it do? And what does it call?
Also what is the %d and what does it do? What is the point of example? Also, how would I call that into code, if at all?
Why can't someone just do the following code to insert the following xml:
<string name="quant">Quantity: </string>
into java like so:
getString(R.string.quant) + quantity
so that way it concactenates the quantity variable into the getString?
Minor typo in your example, there should be a closing tag:
<string name="order_quantity">Cantidad: <xliff:g id="quantity" example="2">%d</xliff:g></string>
The id attribute is just used to identify what the substitution parameter represents (in your case, it represents the quantity). It's as you said, a note, and not actually used programmatically.
That said, in Android Studio, if you have Code Folding enabled for strings, it will substitute in the ID when it shows the collapsed string. You'd see something like this:
// This...
mTextView.setText(getString(R.string.order_quantity, 2));
// Will show as this when folded:
mTextView.setText("Cantidad: {quantity}");
As for your second question, why not just use string concatenation? In other languages, the substitution may not go at the end of the string. You could have something like:
values/strings.xml
<string name="order_quantity">%d items</string>
values-es/strings.xml
<string name="order_quantity">Cantidad: %d</string>
So you can see that in this case, simply appending the strings together would not give you a valid result.
%d is used to represent a part of memory as an integer.
It's most commonly used to print some number to standard output, as follows:
#include <stdio.h>
int main()
{
int n = 42;
printf("The answer to life, universe and everything is %d", n);
return 0;
}
Unlike Java, where you simply concatenate numbers and strings etc., C uses this %something to indicate what is being written. %d indicates, that for example in the printf(), after the comma there will be an argument (in our case it's n), which should be represented as an int.
Refer to List of all format specifiers in C programming for a complete list of format specifiers
Also refer to Official Android Developers Documentation

Using a question mark as a String in android

Im trying to use a question mark as a variable for a string.
I've tried...
strings.xml
<string name="questionMark">\?</string>
.class
String questionMark;
questionMark = getResources().getString(R.string.questionMark);
String delim4 = (questionMark);
This causes a fource close regex error.
and
String delim4 = (\?);
This gets an error Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \ )
and also
I've tried putting 2 backslashes in front of it
String delim4 =(\\?)
System.out.println("delim "+ delim4);
But that just escapes the second slash and sometimes force closes as well.
the output for that was
delim \?
Can any tell me how to put in the question mark as the string. I'm using it as variable to spit a string. The String Im splitting can not be changed.
plz help
Edit added split code
if (FinishedUrl.contains(questionMark)){
String delim3 = (".com/");
String[] parts3 = FinishedUrl.split(delim3);
String JUNK3= parts3[0];
String fIdStpOne = parts3[1];
String fIdStpTwo = fIdStpOne.replaceAll("=#!/","");
String delim4 = (questionMark);
String[] parts4 = fIdStpTwo.split(delim4);
String fIdStpThree= parts3[0];
String JUNK4 = parts3[1];
FId = fIdStpThree;
}
As pointed out by user laalto, ? is a meta-character in regex. You must work around that.
Let's see what's happening here. Firstly, some ground rules:
`?` is not a special character in Java
`?` is a reserved character in regex
This entails:
String test = "?"; // Valid statement in java, but illegal when used as a regex
String test = "\?"; // Illegal use of escape character
Why is the second statement wrong? Because we are trying to escape a character that isn't special (in Java). Okay, we'll get back to this.
Now, for the split(String) method, we need to escape the ? - it being a meta-character in regex. So, we need \? for the regex.
Coming back to the string, how do we get \?? We need to escape the \(backslash) - not the question mark!
Here's the workflow:
String delim4 = "\\?";
This statement gives us \? - it escapes the \(backslash).
String[] parts4 = fIdStpTwo.split(delim4);
This lets us use \? as a regex in the split() method. Since delim4 is being passed as a regex, \? is used as ?. Here, the prefix \ is used to escape ?.
Your observations:
String delim4 = (\?);
This gets an error Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \ )
I covered this above. You are escaping ? at the java level - but it isn't a special character and needs no escaping - hence the error.
String delim4 =(\\?)
System.out.println("delim "+ delim4);
But that just escapes the second slash and sometimes force closes as well. the output for that was
delim \?
This is what we want. It is easier to think of this as a two stage process. The first stage deals with successfully placing a \(backslash) in front of the ?. In the second stage, regex finds that the ? has been prefixed by a \ and uses ? as a literal instead of a meta-character.
And here's how you can place the regex in your res/values/strings.xml:
<string name="questionMark">\\?</string>
By the way, there's another option - not something I use on a regular basis these days - split() works just fine.
You can use StringTokenizer which works with delimiters instead of regex. Afaik, any literal can be used as a delimiter. So, you can use ? directly:
StringTokenizer st = new StringTokenizer(stringToSplit, "?");
while (st.hasMoreTokens()) {
// Use tokens
String token = st.nextToken();
}
Easiest way is to quote or backslash them:
<string name="random">"?"</string>
<string name="random">\?</string>
The final code.
String startDelim = ("\\?");
String realDelim = (startDelim);
String[] parts4 = fIdStpOne.split(realDelim);
String fIdStpTwo= parts4[0];
String JUNK4 = parts4[1];
Normally you'd just put it literally, like
String q = "?";
However, you say you're using it to split a string. split() takes a regular expression and ? is a metacharacter in a regex. To escape it, add a backslash in front. Backslash is a special character in Java string literals so it needs to be escaped, too:
String q = "\\?";

What is the the double quotation marks in strings.xml used for?

Just a little while ago, I was looking around on GitHub, and I found there were some double quotation marks beside the string value in some strings.xml just like this:
<string name="ClipMmi" msgid="6952821216480289285">"来电显示"</string>
In short I mean this
"来电显示"
For full example please click here.
I don't know what is the "" used for? Because if I remove the "" beside the string value (e.g. "来电显示" change to 来电显示), the output won't change any more, both "来电显示" and 来电显示 will print 来电显示 as the output.
So does the quotations make any sense here?
It makes sense on languages that are using simple quotes '.
If simple quotes aren't escaped like this, \', Lint will detect an error.
Using double quotes at the start and at the end of a string value will allow you to omit these backslashes.
There may be other purposes I didn't discovered yet.

Converting String ="0xfbff0000" to int value for using it in Layout.setBackground(int i);

Now, this might seem fairly simple at first, but took good amount of time of mine.
Integer.valueOf(0xfbff0000) wouldn't work, neither would the ParseInt work , i am desperately looking for a solution here.
The Exceptions I get while converting them is NUMBERFORMAT Exception.
I need to use this Hexadecimal value to set background of my layout Dynamically
i.e. Layout.setBackground(int)
Let me clarify that I have a String Variable that looks like String backgroundColor="0xfbff0000";
need this variable backgroundColor to be used as Integer in the Layout.Setbackground(int)
you can use Color.parseColor(String) but you need to replace 0x prefix with #
For instance:
Color.parseColor("#fbff0000");
new Color().parseColor(colorString)
split that string and remove 0x and put the rest in above methods args..
try the following:
int i = Integer.valueOf(myHexString, 16).intValue();

Categories

Resources