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
My application crash whenever pass null value to
Yes, it would. That's the documented behaviour:
Throws:
IllegalArgumentException
- ifnumber
isnull
or not an instance ofNumber
.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With