User's language dependent float representation - android

I am fighting with making my app language dependent. The user needs to enter a float. I am using a EditText to display the current value and allow editing.
To prepare I coded:
st = String.format("%.2f", myFloat);
edTxt = (EditText) findViewById(R.id.myEditText);
edTxt.setText(st, TextView.BufferType.EDITABLE);
edTxt.selectAll();
Now the user is presented the value. If in Settings of my device, I set my language to Deutsch (German) an float value of 2.80 is displayed as 2,80. On onPause of the activity I retrieve the value and convert it from string to float - and get a NumberFormatException error because of the comma.
Should be easy I thought, I just need to replace the comma by a dot, and coded:
String st ="";
st = edTxt.getText().toString();
st.replace(",", ".");
try{
float minV = Float.valueOf(st);
} catch (NumberFormatException nfe){
mShowAToast("NumberFormatException: " + st);
}
And surprise: The app runs into the catch and the toast shows st as "2,80" instead of "2.80", st.replace didn't do its job.
(probably it did, but)
Do I oversee anything?

If you have an float value that use ',' as decimal separator. You can parse it using a Locale class. Check the following code.
public static void main(String[] args) {
try {
// Number and NumberFormat are in java.text.*;
Number numberG = NumberFormat.getNumberInstance(java.util.Locale.GERMAN).parse("-1.234,56");
if (numberG instanceof Double) {
System.out.println(">" + numberG.doubleValue());
}
} catch (ParseException e) {
e.printStackTrace();
}
}
It will print:
>-1234.56
So instead of use java.util.Locale.GERMAN you can use the defaul locale: java.util.Locale.getDefault() of your JVM.
About the replace function of String I have compared the specfication of Android API and Oracle JDK and both are the same. So I think it must return what you expected. Just in case I have tried the folowing in my JDK:
String value = "-1.234,56";
System.out.println(value.replace(',', '.'));
System.out.println(value.replace(",", "."));
And both are printing: -1.234.56

Related

NumberFormat removing comma ( , ) from value?

I have this little crazy method that removes decimal places from string value.
private double getDoubleFromString(final String value) throws ParseException {
NumberFormat format = NumberFormat.getInstance(Locale.getDefault());
Number number = format.parse(value);
return number.doubleValue();
}
It produces values with out comma ( , ) if local language is 'en' it working fine, in other languages that contains , in that strings it's returns value without comma.
Ex :
xx,x
result is xxx.
74,5 --> 745 (problem facing in this format)
74.5 --> 74.5 (working fine it string has dot)
I do need the separator to be a dot or a point and a comma along with value string. Does anybody have a clue of how to accomplish this little feat?
Try this
private double getDoubleFromString(final String value) throws ParseException {
String newvalue= value.replace(",",".");
NumberFormat format = NumberFormat.getInstance(Locale.getDefault());
Number number = format.parse(newvalue);
return number.doubleValue();
}
SAMPLE CODE
try {
Log.e("RESULT_DATA",getDoubleFromString("88,5")+"");
Log.e("RESULT_DATA",getDoubleFromString("79.5")+"");
} catch (ParseException e) {
e.printStackTrace();
}
OUTPUT
03-22 18:37:09.173 7103-7103/? E/RESULT_DATA: 88.5
03-22 18:37:09.174 7103-7103/? E/RESULT_DATA: 79.5

Android slpit string doubleparse and pass it to a method that converts degrres to decimal

I have a android method that converts degrees minutes and seconds to decimal. I am getting the text from edittext split it and convert it to double array before I pass it to the method. Then I wanted to get the double returned in a decimal form to be displayed in the original edittext as string. Here is the code,
public double DegreeToDecimal(double d, double m, double s)
{
double decimal;
decimal = d + m/60 + s/3600;
return decimal;
}
try
{
String string = dtod.getText().toString();
String[] s = string.split(":");
String decimal;
double d = DegreeToDecimal(Double.parseDouble(s[0]), Double.parseDouble(s[1]), Double.parseDouble(s[2]));
decimal = String.valueOf(d);
dtod.setText(decimal);
}catch (Exception e){
e.printStackTrace();
}
When I do this on a button click, nothing happens. The Logcat doesn't show anything and the code is simply ignored. What am I doing wrong?
Thanks for the help.
Your code formatting is all over the place and hard to read, please try to use correct indentation next time!
From the code you posted it's hard to tell what happens. If Logcat doesn't show any stacktraces like you said, and if your code is "ignored" as you say then my guess is that it doesn't get called.
Did you attach an OnClickListener to that button?
Otherwise try to log something between your lines or use a debugger to find out what really happens!

Get EditTextValue and parse it into a decimal with only one digit for integer part

I'm having an issue when I get a whole number from an EditText and try to change that to a decimal so I can use it for calculations. Could someone explain how to do this?
For Example. if someone was to enter 120 into the EditText and I got the integer from it, how would I then change that integer of 120 into 1.20 and continue calculations with it?
Thanks!!
EditText myEditText = (EditText)findViewById(R.id.YOUR_EDIT_TEXT_ID);
String numberAsString = myEditText.getText().toString();
double myDecimal;
try {
myDecimal = Double.parseDouble(numberAsString);
if (myDecimal >= 10)
{
int digits = 1 + (int)Math.floor(Math.log10(myDecimal));
myDecimal = myDecimal / ((Math.pow((double)10, ((double)digits) - 1)));
System.out.println(myDecimal);
}
} catch (NumberFormatException e) {
//handle exeption
e.printStackTrace();
}
You need to get the contents from your EditText as a string, and from there you can parse it into an integer. This is done like so:
int wholeNum = Integer.parseInt(yourEditText.getText().toString());
int three = Integer.parse("3");
I know you can use this to parse a string into an integer, there is probably a parse method in double aswell!
Check this also :
Convert a String to Double - Java
+1 to anthony for answering 1 minute before me haha

read ViewText convert to double

My app has a number of numeric user input fields which need sanity checks before proceeding to the next intent.
I read viewText fields, convert them to double and then do the (numeric) tests but odd things happen and I find that while the code runs on my HTC in debug, it falls over if I publish then download the published version. My code is sumarised as;
String sFy;
double mFy=0;D
sFy=(txtFy.getText().toString());
mFy=Double.parseDouble(sFy);
if sFy is null the .parsedouble crashes. If I use;
sFy=(txtFy.getText().toString());
mFy=getDouble(sFy);
private double getDouble(String string){
double temp=0.0;
try {
temp = Double.parseDouble(string.trim());
} catch(NumberFormatException nfe) {
System.out.println("getDouble, Could not parse " + nfe);
}
return temp;
}
it works, even if sFy is empty.
Can anyone tell my why, or suggest a 'correct' method?
Maybe like that :
String sFy;
double mFy=0;
sFy = txtFy.getText();
if ((sFy != ""){
mFy=Double.parseDouble(sFy);
}
Or maybe I haven't really understood your problem...
Your getDouble is returning 0.0 in case there is NumberFormatException.
Do you see debugger coming to System.out.println("getDouble, Could not parse " + nfe);

Change value of R.string programmatically?

I'm looking for a way to change the value of a string resource dynamically. I have tried to use reflection but it claims 'invalid value for field'.
I use the strings for values within the layout, but need to swap them out for different languages.
Please see the attached code below.
public class Lang{
public static void langInit(){
java.lang.reflect.Field[] langStringFields = R.string.class.getFields();
Log.d(Global.TAG,"--> Lang Listing: " + langStringFields.length);
Log.d(Global.TAG,"--> Pref for language:");
String prefInLang = Prefs.cPrefsGet.getString("in_lang","en");
String fieldName = null;
String fieldValue = null;
String newFieldName = null;
String tmpA = "one";
for (int i=0; i<langStringFields.length; i++){
java.lang.reflect.Field field = langStringFields[i];
fieldName = field.getName();
try {
fieldValue = Global.gActivity.getString(field.getInt(R.string.class));
} catch (Exception e) {
e.printStackTrace();
}
if (fieldName.substring(0,2).equals("lo")){
try {
newFieldName = R.string.class.getField(prefInLang + "_" + fieldName.substring(3)).getName();
} catch (Exception e) {
e.printStackTrace();
}
Log.d(Global.TAG,"--> Field: " + fieldName + "value: " + fieldValue + "new field:" + newFieldName);
try {
java.lang.reflect.Field field2 = Class.forName(R.string.class.getName()).getDeclaredField(newFieldName);
field2.setAccessible(true);
field2.set(R.string.class,tmpA.toString());
}catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
Use built-in mechanism of localization, introduced in android. You don't need to change anything. You just need to specify the new strings.xml for each locale.
If you want to change current language for you app you can do it by using standard built-in localization features and changing locale programatically.
you should rather add a locale value to your resources and duplicate them : one for each language, thus letting the device choose the right one according to it's settings : check it there http://developer.android.com/resources/tutorials/localization/index.html
I believe using Android's built-in localization features is preferable to implementing it by hand. Here's a guide you can refer to:
http://developer.android.com/guide/topics/resources/localization.html
Unless, of course, we misunderstood your use case, but it does really sound like you are trying to do standard localization :-)
Bruno Oliveira, Developer Programs Engineer, Google

Categories

Resources