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.
It will print:
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:
And both are printing: -1.234.56