String.format uses comma instead of point

核能气质少年 提交于 2019-12-05 01:43:23

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:


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.

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

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.

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 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!