-2
我有一些格式化給定數字的代碼。代碼格式基於用戶配置文件中設置的區域設置。如果用戶輸入諸如551 $ 44之類的「破碎」數字,則只有551被返回而44被忘記。我需要一種方法讓$被拉出並顯示55144。Java.text.NumberFormat解析方法不能正確解析語言環境
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));
}
}
是有沒有任何可能的方法來解析用戶決定的語言環境,並保留所有數字,而不管用戶輸入什麼內容?
用戶輸入號碼在哪裏?一個'JTextField',一個文件,...?如果它是'JTextfield',你可以添加一個'Document'來過濾掉無效字符。 –