Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are numbers with a leading sign (plus or minus) when converted to BigDecimal, treated as valid numbers in Java?

The following expressions are valid in Java as obvious

int a = -0;
int b = +0;

and so are the following.

Integer c = new Integer(-0);
int d = Integer.parseInt("-0");
BigDecimal e = new BigDecimal("-0");

The following statements are however invalid.

Integer f = new Integer("+0");   //Leading + sign.
int g=Integer.parseInt("+0");    //Leading + sign.

Both of them throw the NumberFormatException.

The following statement with BigDecimal however compiles and runs without causing an exception to be thrown.

BigDecimal bigDecimal = new BigDecimal("+0");  //Leading + sign.

Why is a leading + sign valid with BigDecimal here which however doesn't appear to be the case with the other datatypes available in Java?

like image 340
Tiny Avatar asked Oct 22 '12 02:10

Tiny


1 Answers

According to the documentation, negative signs needs the minus sign. But if its a positive Integer, no need for a plus sign.

public static int parseInt(String s)

The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method.

Then for the constructor:

public Integer(String s)

The string is converted to an int value in exactly the manner used by the parseInt method for radix 10.

like image 131
Russell Gutierrez Avatar answered Nov 14 '22 21:11

Russell Gutierrez