Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 903
jiraiya Avatar asked Mar 07 '11 15:03

jiraiya


People also ask

Can null be a default value?

If no default value is declared explicitly, the default value is the null value. This usually makes sense because a null value can be considered to represent unknown data. In a table definition, default values are listed after the column data type.

How do I remove blank columns in Jasper report?

Just collapse it down to the left first then the columns to the right will be the blank ones. Vote up!


1 Answers

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".

like image 150
Dave Jarvis Avatar answered Sep 23 '22 19:09

Dave Jarvis