7

可能的重复:
安全和区域敏感地解析数字

如何以区域设置敏感的方式验证包含十进制数字的字符串?NumberFormat.parse 允许太多,而 Double.parseDouble 仅适用于英语语言环境。这是我尝试过的:

public static void main(String[] args) throws ParseException {
    Locale.setDefault(Locale.GERMAN);

    NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.getDefault());
    Number parsed = numberFormat.parse("4,5.6dfhf");
    System.out.println("parsed = " + parsed); // prints 4.5 instead of throwing ParseException

    double v = Double.parseDouble("3,3"); // throws NumberFormatException, although correct
}
4

2 回答 2

2

关于

Number parsed = numberFormat.parse("4,5.6dfhf");

问题,您可以使用NumberFormat.parse(String source, ParsePosition pos)并检查它停止解析的位置是否确实是字符串的最后一个位置。

此外,在 4.5.6 问题上,您可以尝试通过setGroupingUsed(boolean newValue)设置分组,因为我认为这是由“。”产生的问题。字符是语言环境中的分组字符。

它应该是这样的

NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.getDefault());
numberFormat.setGroupingUsed(false);
ParsePosition pos;
String nString = "4,5.6dfhf";

Number parsed = numberFormat.parse(nString, pos);
if (pos.getIndex() == nString.length()) // pos is set AFTER the last parsed position
   System.out.println("parsed = " + parsed);
else
   // Wrong
于 2013-01-07T11:33:54.163 回答
1

从您上面的评论中,您可以使用:

String input = "3,3"; // or whatever you want
boolean isValid = input.matches("^\\d+([.,]\\d+)?$");
double value = Double.parseDouble(input.replaceAll(",", "."));

如果分隔符可以是逗号以外的其他内容,只需将其添加到方括号中:

double value = Double.parseDouble(input.replaceAll("[,]", "."));
于 2013-01-07T11:30:08.860 回答