I would like to parse decimal numbers in Java with plus sign, minus sign or no sign and get an instance of BigDecimal
. This can be achieved simply by calling constructor new BigDecimal(string)
. It produces appropriate results for all of the following strings:
"1", "12", "123", "123.0", "+123.0", "-123.0", "+123", "-123"
However, I need to parse the strings according a specific locale, i.e. with comma decimal separator. Is there a way to parse all these numbers with respect to a particular locale?
I tried NumberFormat
and DecimalFormat
but cannot configure it appropriately.
final DecimalFormat valueParser = (DecimalFormat) NumberFormat.getNumberInstance(new Locale("cs"));
valueParser.setParseBigDecimal(true);
Such valueParser
does not accept the plus sign. There is an option to set a pattern to DecimalFormat
. However, can the plus sign be specified as optional in the pattern?
The java. text. DecimalFormat class is used for formatting numbers as per customized format and as per locale.
The %. 2f syntax tells Java to return your variable (value) with 2 decimal places (. 2) in decimal representation of a floating-point number (f) from the start of the format specifier (%).
DecimalFormat isn't thread-safe, thus we should pay special attention when sharing the same instance between threads.
You can create a DecimalFormat that accepts or better requires a leading "+".
DecimalFormat f (DecimalFormat)NumberFormat.getNumberInstance(new Locale(...));
f.setPositivePrefix("+");
f.parse("+123");
However the prefix is not optional therefore it does not help your case. As a very simple solution, why don't you check the (trimmed) string if starts with a '+' character and in that case cut of the leading '+' before you pass the string to the DecimalFormats parse method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With