Extra plus sign with java.text.DecimalFormat
I would like to parse decimal numbers in Java with plus sign, minus sign or unsigned and get an instance BigDecimal
. This can be achieved simply by calling the constructor new BigDecimal(string)
. It gives corresponding results for all of the following lines:
"1", "12", "123", "123.0", "+123.0", "-123.0", "+123", "-123"
However, I need to parse the strings according to a specific locale, that is, with a semicolon separator. Is there a way to parse all these numbers relative to a particular locale?
I tried NumberFormat
and DecimalFormat
but couldn't configure it appropriately.
final DecimalFormat valueParser = (DecimalFormat) NumberFormat.getNumberInstance(new Locale("cs"));
valueParser.setParseBigDecimal(true);
It valueParser
doesn't take a plus sign. It is possible to install a template DecimalFormat
. However, can the plus sign be specified as optional in a template?
source to share
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, so it won't help your case. As a very simple solution, why don't you check the (truncated) string if it starts with a "+" and in that case cut the leading "+" before passing the string to the DecimalFormats parse method.
source to share