Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal Format null handling

Tags:

java

I am using Java 1.6 and we are using java.text.DecimalFormat to format numbers. For example

    DecimalFormat df = new DecimalFormat();
    df.setPositivePrefix("$");
    df.setNegativePrefix("(".concat($));
    df.setNegativeSuffix(")");
    df.setMaximumFractionDigits(2);
    df.setMinimumFractionDigits(2);
    df.setGroupingSize(3);

    df.format(new java.math.BigDecimal(100);

My application crash whenever pass null value to df.format(null)

Error: cannot format given object as a number 

My question is, how can I handle null value in df.format() function ?

I would like to pass null to df.format() function and would want it to return 0.00 instead of above error.

Thanks You

Regards,

Ankush

like image 890
Ankush Chhabra Avatar asked Oct 20 '25 13:10

Ankush Chhabra


1 Answers

My application crash whenever pass null value to

Yes, it would. That's the documented behaviour:

Throws: IllegalArgumentException - if number is null or not an instance of Number.

Next:

I would like to pass null to df.format() function and would want it to return 0.00 instead of above error.

No, that's not going to work. It's documented not to work. Just don't pass null in... it's easy enough to detect. So you could use this:

String text = value == null ? "0.00" : df.format(value);

Or

String text = df.format(value == null ? BigDecimal.ZERO : value);
like image 59
Jon Skeet Avatar answered Oct 22 '25 03:10

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!