When it comes to parsing numbers with decimal separators from string, Wicket’s BigDecimalConverter behaves differently than BigDecimal’s (String val) constructor.
Let’s try to parse a number with comma as the decimal separator using US locale. (I’m using Wicket 1.4.14 BTW.)
new BigDecimalConverter().convertToObject("1,3", Locale.US)
returns 13,
but
Locale.setDefault(Locale.US);
new BigDecimal("1,3")
throws NumberFormatException.
Why doesn’t BigDecimalConverter behave the same way as BigDecimal in this case? The number “1,3” doesn’t make sense for the US locale.
The
BigDecimalclass implements its own validation algorithm on the input, which is throwing theNumberFormatException.The reason why
BigDecimalConverteris parsing1,3as13is that it is using a rawDecimalFormatbehind the scenes. InAbstractNumberConverter.parse(), thegetNumberFormat(locale)andparse()methods combination boils down to the following snippet, that takes Wicket out of the equation:UPDATE
The reason why
DecimalFormatis ignoring the,character is because it is defined as the grouping separator in theDecimalFormatSymbolsfor the US locale.It is permitted, and legal as it would be in
1,300.5.In case you want to avoid converting
1,3to13, and throwing a invalid format conversion exception, you could overrideBigDecimalConverter.getNumberFormat(Locale)in order to modify theDecimalFormatto not use grouping, use a different grouping symbol, or use a more restrictive pattern. For instance:Note: Use the above example with caution, create a class for the Converter so it doesn’t get instantiated at each call of
getConverter()and don’t modify theNumberFormatinstanceBigDecimalConverter.getNumberFormat()returns, it might be a global shared instance.Just to add, this is the exact piece of code that’s ignoring the
,character for being a group separator:DecimalFormat.subparse()branch in line 1522. With input of1,3, the comma is ignored, beingisGroupingUsed()true.