This might look like a repeated question but I tried in all the below links and can't get a proper answer.
Cannot format given Object as a Number ComboBox
But I'm not getting whats wrong. Here is my code
DecimalFormat twoDForm = new DecimalFormat("#.##");
double externalmark = 1.86;
double internalmark = 4.0;
System.out.println(String.valueOf((externalmark*3+internalmark*1)/4));
String val = String.valueOf((externalmark*3+internalmark*1)/4);
String wgpa1=twoDForm.format(val); // gives exception
String wgpa2=twoDForm.format((externalmark*3+internalmark*1)/4)); // works fine
System.out.println(wgpa1);
The format
method takes Object type argument, so that's why I passed a String object which gives exception
Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object as a Number.
But when I give double value as argument the program works fine. But if the method is defined with Object
type argument why I'm getting an exception while passing a String
and not getting exception while passing double
?
The
format()
method ofDecimalFormat
is overloaded.In the working case, you are invoking :
And in the failing case, you are invoking :
The first method takes a very specific argument. It expects a
double
.This is not the case of the second one, which the type accepted is very broad :
Object
and where so the check on the type passed is performed at runtime.By providing a argument that is not a
double
but aString
, the method invoked is the second one.Under the hood, this method relies on the
format(Object number, StringBuffer toAppendTo, FieldPosition pos)
method that expects to anumber
argument that is an instance of theNumber
class (Short
,Long
, ...Double
):But it is not the case as you passed to it a
String
instance.To solve the problem, either pass a
double
primitive as in the success case or convert yourString
into an instance ofNumber
such asDouble
withDouble.valueOf(yourString)
.I advise the first way (passing a
double
) as it is more natural in your code that already usesdouble
primitives.The second one requires a additional conversion operation from
String
toDouble
.The answer is in the javadoc. It says clearly, "The number can be of any subclass of Number", and it says that it throws
IllegalArgumentException
"if number is null or not an instance of Number."(So why don't they just make the parameter a
Number
type? Because the class is a subclass of the abstractFormat
class that isn't restricted to numeric formatting. The expectation, apparently, is that while the generalFormat
class has a method with anObject
parameters, subclasses ofFormat
are expected to limit the parameters to the object types that they can handle, which they have to do at run time.)