我有一些格式化给定数字的代码。基于用户配置文件中设置的区域设置的代码格式。如果用户输入一个“损坏的”数字,例如 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 并将其与逗号进行比较。然后它检查以查看小数分隔符的索引,然后将语言环境更改为使用 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));
}
}
是否有任何可能的方法来解析用户决定的语言环境并保留所有数字,无论用户键入什么?