Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional plus sign with java.text.DecimalFormat

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?

like image 613
Cimlman Avatar asked Jul 07 '15 10:07

Cimlman


People also ask

What is the use of DecimalFormat in Java?

The java. text. DecimalFormat class is used for formatting numbers as per customized format and as per locale.

How do you do 2 decimal places in Java?

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 (%).

Is DecimalFormat thread safe?

DecimalFormat isn't thread-safe, thus we should pay special attention when sharing the same instance between threads.


1 Answers

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.

like image 132
wero Avatar answered Oct 22 '22 00:10

wero