Locale userLocale = Locale.forLanguageTag("uk-UK");
DecimalFormat decimalFormat = (DecimalFormat) NumberFormat.getInstance(userLocale);
decimalFormat.setParseBigDecimal(true);
System.out.println(decimalFormat.parse("123456,99").toString()); // output: 123456.99 -> it's OK
System.out.println(decimalFormat.parse("123456Test99").toString()); // output: 123456 -> it's BAD
最后输入的ParseException。
我当前的尝试:
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
import static java.lang.Character.isDigit;
private BigDecimal processNumber(DecimalFormat numberFormat, String rowValue) throws ParseException {
BigDecimal value = null;
if (rowValue == null) return null;
final char groupingSeparator = numberFormat.getDecimalFormatSymbols().getGroupingSeparator();
final char decimalSeparator = numberFormat.getDecimalFormatSymbols().getDecimalSeparator();
final char minusSign = numberFormat.getDecimalFormatSymbols().getMinusSign();
for (char ch : rowValue.toCharArray())
if (!isDigit(ch) && ch != decimalSeparator && ch != groupingSeparator && ch != minusSign)
throw new ParseException("", 0); // wrong pos, I know, but it's excessively here
if (!rowValue.isEmpty())
value = new BigDecimal(numberFormat.parse(rowValue).toString());
return value;
}
以下是我使用ParsePosition
找出解析结束位置的示例。如果未解析整个输入字符串,则会显示错误。
String string1 = "123456,99";
String string2 = "123456Test99";
Locale userLocale = Locale.forLanguageTag("uk-UK");
DecimalFormat decimalFormat = (DecimalFormat) NumberFormat.getInstance(userLocale);
decimalFormat.setParseBigDecimal(true);
ParsePosition parsePosition = new ParsePosition(0);
Number number1 = decimalFormat.parse(string1, parsePosition);
if (parsePosition.getIndex() < string1.length()) {
System.out.println("Parse error");
} else {
System.out.println(number1.toString());
}
parsePosition = new ParsePosition(0);
Number number2 = decimalFormat.parse(string2, parsePosition);
if (parsePosition.getIndex() < string2.length()) {
System.out.println("Parse error");
} else {
System.out.println(number2.toString());
}
生成的输出:
123456.99
Parse error