Am writing an android code where a text view is being populated by a calculated % inside my java class.
As i had to calulate the %, my final variable (calcPerc) is a double type of variable. It wont setText into my TextView.
Please help.
Code
int totDiff = (totalMA - totalIA);
double beforeperc = ((double)totDiff / (double)totalIA);
calPerc = ((double)beforeperc*100);
percentage = (TextView)findViewById(R.id.populatePercentage);
percentage.setText(calPerc);
The error i am getting is
The method setText(CharSequence) in the type TextView is not applicable for the arguments (double)
Also, one more followup question. The variable "calPerc" as it is double, gives me infinite digits after the decimal. How do i round it off to 2 decimals only?
This should format the value for display (with max 2 decimals) correctly for your current locale;
NumberFormat twoDecimals = NumberFormat.getInstance();
twoDecimals.setMaximumFractionDigits(2);
percentage.setText(twoDecimals.format(calPerc));
To have more control over formatting (like limiting the number of digits after the decimal point), you can use String.format():
percentage.setText(String.format("%.2f %%", calPerc));
But be wary of the default locale.
Related
I am writing code in Adobe Flash Builder for an Android application. I have written my code to do some math and return the answer to a label field. I would like to know how do I return this answer to show only 1 spot after the decimal. Here is the code
lblAnswer.text = String(Number ((sldrABSL.value) + 46.7)/28.7);
If there are any suggestions please let me know.
If I understand this correctly, you have a string representing a number, which you want to be presented with only one decimal.
Fist of all, you'd have to convert the numeric value of the string to a double:
String stringOfNumber = "100.1233123";
Double number = Double.valueOf(stringOfNumber);
Secondly, you'd have to establish the format of which to represent the double (number of decimals):
DecimalFormat oneDigit = new DecimalFormat("#,##0.0");
Set the digit to a (i.e) TextView:
myTextView.setText("" + oneDigit.format(number));
I think this should work. Is this kind of what you were asking?
Edit: Not super certain as to how to set it to a textview, but in java, printing it to screen works like this:
System.out.println(oneDigit.format(number));
Edit2: Oh, and you'll need to this import:
import java.text.DecimalFormat;
Edit3:
TextView.setText("" + oneDigit.format(number));
works fine for me.
The decimal places uses the tofixed property. It must be added at the end of the specified number that needs to contain the decimal place.
'lblAnswer.text = String(Number ((sldrABSL.value) + 46.7)/28.7).toFixed(1);
The one specifies the number of decimal places that are used.
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);
I faced an interesting problem today. I have 4 strings which I need to show on app on random basis. So I simply added the strings to my string.xml and was setting my textview to show the text as
textView.setText(R.string.text_1);
or (if random number was 2)
textView.setText(R.string.text_2);
and so on
I observed that the change is just in last character, so tried using reflection
Class c = Class.forName("com.startpage.mobile.R$string");
Field field = c.getDeclaredField("text_"+num); //num is 1/2/3/4
System.out.println("********** "+field.get(null));
Now the field.get(null) actually return the Id (hexadecimal number in R.java) value instead of string value I would expect.
Is there a way to fetch actual value of string using reflection or this is something in android which I will have to live with?
getResources.getString(resourceId);
R.string.text_2
will always return the hex number. To really get the string value, you have to try the following
MyActivity.this.getResources.getString(R.string.text_2);
You can simply request your resource ID from the resource manager:
Class c = Class.forName("com.startpage.mobile.R$string");
Field field = c.getDeclaredField("text_" + num);
int resId = (int)field.get(null);
String text = this.getResources().getString(resId);
textView.setText(text);
I suggest you to use array of strings and choose random item from it
My app is working on many devices without problems so far. But now I got my new Galaxy Tab with Android 3.2 where it crashes all the time. I found out that the problem was a float in an EditText.
I am using myEditText.setText(String.format("%.1f", fMyFloat)); to put the float in the EditText. But somehow the float on my 3.2 Galaxy Tab is generated with a comma instead of a point. When I read the EditText back the app crashes of course, telling me that this is no valid float because of the comma...
What is going wrong here?
Convert float to string..
From the documentation of String.format:
String.format(String format, Object... args)
Returns a localized formatted string, using the supplied format and arguments, using the user's default locale.
The quoted text above means that the output of String.format will match the default locale the user uses.
As an example a comma would be used as the decimal-point-delimiter if it's a user using Swedish locale, but a dot if it's using an American.
If you'd like to force what locale is going to be used, use the overload of String.format that accepts three parameters:
String.format (Locale locale, String format, Object... args)
Convert string to float..
Parsing an arbitrary string into a float using the default locale is quite easy, all you need to do is to use DecimalFormat.parse.
Then use .parse to get a Number and call floatValue on this returned object.
Your format call on your Galaxy Tab uses some default Locale which in turn uses , for floats. You could use String.format(Locale,String,...) version with specific locale to make things work.
Or you should've used same locale both for parsing and formatting the number. So you should probably go with NumberFormat to format and parse your floats.
String.format uses the locale you are in. You should do something like this if you want a dot:
NumberFormat formatter = NumberFormat.getInstance(Locale.US);
myEditText.setText(formatter.format(fMyFloat);
Have a look into NumberFormat for more formatting options
Use below code it's works for me:
NumberFormat nf = NumberFormat.getNumberInstance(Locale.US);
DecimalFormat df = (DecimalFormat)nf;
df.applyPattern(pattern);
String output = df.format(value);
System.out.println(pattern + " " + output + " " + loc.toString());
Summing up previous answers, an easy way to have the dot instead of the comma in all country, is this:
myEditText.setText(Locale.CANADA, String.format("%.1f", fMyFloat));
And you will have your String formatted with the dot
Here is my formula:
(R.id.dch135-(R.id.drg59*.0752)-(R.id.drg6*.061)-(R.id.drg11*.0412)-(R.id.dplenum*.0802)-(R.id.s2way*4.5)-(R.id.s3way*6.9)-(R.id.sbal35*4.5)-(R.id.sunbal70*8.8)-(R.id.s4way*8.8)-(R.id.s8way*13)-(R.id.sdc6th*3.3)-(R.id.sdc9th*2.7)-(R.id.sdc12th*2)-(R.id.sdc6tp*6)-(R.id.sdc9tp*9)-(R.id.sdc12tp*12)-(R.id.samp*14.5)
I have editText boxes on several layouts. I want to run the formula above on them and get a result to display on a editText box on another layout called results.
I have tried using the getText but all I get back is "Cannot invoke setText(String) on the primitive type int".
Any help would be great!
Thanks
It seems that when you say (R.id.drg59*.0752) you mean "get the value from the EditText with ID drg59 and multiply if by 0.0752. However, what that means in Java is "multiply the value R.id.drg59 (an integer value defined in R.java, not whatever is currently in your edittext) by 0.0752".
You need to parse each of the EditText values to a number (a float, presumably) and THEN multiply it by the 0.0752. For example:
EditText drg59Text = (EditText) findViewById(R.id.drg59);
float drg59Value = Float.parseFloat(drg59Text.getText());
float result = drg59Value * 0.0752;
So on and so forth.
Also, when setting the text value you need to convert the value to a string, the easiest way is generally to just append you value to an empty string:
EditText resultText = ...
resultText.setText("" + result); //where "result" is a float value