String to double locale error
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 */
}
精彩评论