String.format使用逗号而不是点 [英] String.format uses comma instead of point
问题描述
我正在使用
myEditText.setText(String.format(%。1f,fMyFloat));
将浮点数放到EditText中。但不知何故,我的3.2 Galaxy Tab上的浮点数是用逗号而不是点数来生成的。当我阅读EditText的时候,应用程序崩溃,当然,告诉我,这是无效的浮动,因为逗号... 这里出了什么问题? p>
将float转换为字符串..
c $ c> String.format :
String.format(String format,Object。 .. args)
返回一个本地化的格式化字符串,使用提供的格式和参数,使用用户的默认语言环境。
上面引用的文本表示 String.format
的输出将匹配默认语言环境用户使用。
例如,如果使用瑞典语区域设置的用户使用逗号作为小数点分隔符,但是如果使用逗号g美国人。
$ b
如果您想要强制使用哪种语言环境,请使用的重载String.format
接受三个参数:
- String.format(Locale locale,String格式,Object ... args)
$ b $ h $>将字符串转换为浮点数。
使用默认语言环境将任意字符串解析为浮点数非常简单,只需使用 DecimalFormat.parse
。
然后使用 .parse
得到一个 数字
并调用 floatValue
返回的对象。
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?
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使用逗号而不是点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!