Formatting using DecimalFormat throws exception - "Cannot format given Object as a Number"

Viewed 46688

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

Illegal Argument Exception

But I'm not getting what's 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?

3 Answers

If there is any mathematical calculation then using java.math.BigDecimal class's methods are the better choice for accuracy in result and efficient in performance even numbers are too large. Using java.math.BigDecimal code :

double externalmark1 = 1.86;
double internalmark2 = 4.0;
System.out.println(String.valueOf((externalmark1*3+internalmark2*1)/4));
System.out.println("------------------------");

BigDecimal decimalValue1 = new BigDecimal((externalmark1*3+internalmark2*1)/4).setScale(2, RoundingMode.HALF_UP);       
System.out.println("aggregatemark [direct decimalValue]: "+decimalValue1.toString());
System.out.println("------------------------");

double aggregatemark = (externalmark1*3+internalmark2*1)/4;
System.out.println("aggregatemark [double]: "+aggregatemark);       
BigDecimal decimalValue2 = new BigDecimal(aggregatemark).setScale(2, RoundingMode.HALF_UP);     
System.out.println("aggregatemark [decimalValue]: "+decimalValue2.toString());
System.out.println("------------------------");

String aggregatemarkStr = String.valueOf((externalmark1*3+internalmark2*1)/4);
System.out.println("aggregatemark [string] : "+aggregatemarkStr);       
BigDecimal decimalValue3 = new BigDecimal(aggregatemarkStr).setScale(2, RoundingMode.HALF_UP);      
System.out.println("aggregatemark [decimalValue]: "+decimalValue3.toString());
Related