String.format uses comma instead of point

2020-08-09 10:36发布

问题:

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?

回答1:

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.



回答2:

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



回答3:

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.



回答4:

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());


回答5:

Summing up previous answer, 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