Given:
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
Expected:
ParseException on last input.
- Why not fail fast check was chosen by jdk's developers?
- How do you handle such cases?
My current attempt:
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;
}
parse(String, ParsePosition)? I only just did a quick read, but it seemsParsePositionwill indicate at which position the parsing ended. If this end position is before the end of the provided string, not the whole string was parsed and you may treat that as an error.