Search code examples
jasper-reportstextfieldireport

Default value for null fields in a Jasper Report


Background

A ResultSet has many Double value fields (with patterns like "###0.000"). Some values can be null.

Problem

I want to replace null values with "N/A", which is a String and cannot print to a Double field. Printing "0.00" for null values is unacceptable.

Using an PrintWhenExpression value of ($F{value} != null) ? $F{value} : "N/A" does not work; it is not possible to use patterns in that way.

Idea

Add hidden fields that write "N/A". These fields will be printed only if value is null.

Question

Is there a better solution, and if so, what is it?

Thank you.


Solution

  • Solution #1

    Your solution:

    1. Use a regular Double field (doubleField) for the column value.
    2. Add a static String text field at the same location.
    3. Change the Double field to Blank When Null.
    4. Set the PrintWhenExpression value for the String text field to: $F{doubleField} == null.

    Solution #2

    The problem is, as you pointed out, that a Double and a String are two different data types. You can assign a String variable to the value of the Double using an appropriate expression. Then use the String variable as the field. The expression might resemble:

    ($F{doubleField} == null) ?
      "N/A" : new java.text.DecimalFormat("#.##").format($F{doubleField})
    

    (Note: My preference is to use == instead of !=. Think positive.)

    Solution #3

    Change the SQL statement to pre-format the Double as a text string, and use the "N/A" in the string (by using a CASE or DECODE statement in the query).

    Avoid this solution, though, as it is not maintainable.

    Recommendation

    Do not hard-code the "N/A" string throughout the report(s); put the "N/A" text in a constant, or a parameter with a default value of "N/A".