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?
In java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string. Parameter: The locale value to be applied on the format() method.
locale which is the locale value to be applied on the this method. format which is the format according to which the String is to be formatted. args which is the number of arguments for the formatted string. It can be optional, i.e. no arguments or any number of arguments according to the format.
format("%,. 2f", numParsed); For the format string "%,. 2f" - "," means separate digit groups with commas, and ".
If you want to change formatting symbols, such as the decimal separator, you can use the DecimalFormatSymbols in conjunction with the DecimalFormat class. These classes offer a great deal of flexibility in the formatting of numbers, but they can make your code more complex.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With