Java.text.NumberFormat解析方法无法正确解析语言环境

时间:2013-08-28 13:01:55

标签: java junit

我有一些格式化给定数字的代码。代码格式基于用户配置文件中的设置区域设置。如果用户输入“损坏”的数字,例如551 $ 44,则仅返回551并且忘记44。我需要一种方法来取出$并显示55144。

static double formatNumber(String number, Locale locale, char decimalSeparator) throws ParseException {
    double rtn = 0.0;
    if (decimalSeparator == ',') {
        if (number.indexOf(decimalSeparator) == -1) {
            rtn = NumberFormat.getNumberInstance(new Locale("en")).parse(number).doubleValue();
        } else {
            rtn = NumberFormat.getNumberInstance(locale).parse(number).doubleValue();
        }
    } else {
        if (number.indexOf(decimalSeparator) == -1) {
            rtn = NumberFormat.getNumberInstance(new Locale("fr")).parse(number).doubleValue();
        } else {
            rtn = NumberFormat.getNumberInstance(locale).parse(number).doubleValue();
        }
    }
    return rtn;
}

该代码是格式化程序,它检查decimalSeparator对于语言环境的含义并将其与逗号进行比较。然后它检查以查看decimalSeparator的索引,然后更改语言环境以使用en。我编写了一个检查多个“损坏”数字的测试,当它涉及“1.478,451,0”时它失败了,因为它拉出逗号并停止而不是添加4510.

@Test
public void testFormatBrokenNumbersENCA() throws ParseException {
    Locale locale = new Locale("en_CA");
    Double[] parsedNumbers = { 0.0, 0.0, 0.0, 1.0, 1.0, 1.478451, 1.1,
            1.1, -1.0, -1.0, -1.0, 3.141592653589793, (double) 111555999 };
    String[] numbers = { "0     ", "0.,,,,,0", "0,,,,,0", "1,,", "1.m0",
            "1.478,451,0", "1.1.1", "1,1,1", "-1-", "-1.0-", "-1,0+-",
            "3.141592$65,35%89793", "111 555 999" };
    String[] failures = { "0     was passed in", "0.,,,,,0 was passed in",
            "0,,,,,0 was passed in", "1,, was passed in",
            "1.m0 was passed in", "1.478,451,0 was passed in",
            "1.1.1 was passed in", "1,1,1 was passed in",
            "-1- was passed in", "-1.0- was passed in",
            "-1,0-+ was passed in", "3.141592$65,35%89793 was passed in",
            "111 555 999 was passed in" };

    for (int i = 0; i < parsedNumbers.length; i++) {
        assertEquals(failures[i], parsedNumbers[i],
                Validation.getNumber(numbers[i], locale));
    }

}  

是否有任何可能的方法解析用户决定的语言环境并保留所有数字,无论用户输入什么类型?

1 个答案:

答案 0 :(得分:1)

您可以检查解析位置是否到达结尾。如果不删除解析位置的字符。使用明确ParsePosition

的解析
for (;;) {
    ParsePosition pos = new ParsePosition(0);
    nf.parse(number, pos);
    if (pos.getErrorIndex() != -1) { // In fact for the exception catch.
        break;
    }
    int i = pos.getIndex();
    if (i == number.length()) { // Did all.
        break;
    }
    number = number.substring(0, i) + number.substring(i + 1);
}