开发者

String to double locale error

开发者 https://www.devze.com 2023-03-31 06:53 出处:网络
In my app, I use text boxes for entering decimal number values. From there, I use Double.valueOf(); to get the value as a double. This works fine, except some users with different locales are get

In my app, I use text boxes for entering decimal number values.

From there, I use

Double.valueOf();

to get the value as a double. This works fine, except some users with different locales are getting errors.

How do I make sure this doesn't happen? Also, should I be using 开发者_运维技巧Double.ParseDouble() or Double.valueOf()?

Thanks.


I use the following Java methods to parse a double that has been typed by the user and stored in string s.

However, I know the locale the user is using. If you do not know then it is difficult to be certain how to parse the number because a value such as "100.000" means different things in different locales.

NumberFormat numberFormat = DecimalFormat.getInstance(locale);
numberFormat.setGroupingUsed(false);
ParsePosition parsePosition = new ParsePosition(0);
Number n = numberFormat.parse(s, parsePosition);
if (n == null || parsePosition.getErrorIndex() >= 0 || parsePosition.getIndex() < s.length())
{
  /* not a valid number */
}
0

精彩评论

暂无评论...
验证码 换一张
取 消