Number format a decimal in Birt reports

Saurabh Singhal picture Saurabh Singhal · Apr 4, 2014 · Viewed 12.9k times · Source

I have a table which gives me values in Nos. and Decimal (weight-kg) E.g.10.455 Kg ( that is 10 Kg and 455 gms) and nos. as in 10 Nos.

Now all these values come from a column (Decimal (10,3)-mysql) in table and based on the unittype column I have to decide whether to have 3 decimal or zero decimal in the BIRT report.

I know that through scripting the values can be modified.. but I am unable to utilise the scripting.

I am writing this on onFetch

if(row["unittype"]=="Nos")
var df = new Packages.java.text.DecimalFormat("#,###.##");
else
var df = new Packages.java.text.DecimalFormat("#,###");

df.format(row["invoicedquantity"]);
this.setDisplayValue(df);

I am unable to get the values

Answer

Dominique picture Dominique · Apr 4, 2014

I don't believe this can work from the onFetch script, this kind of script should be put in "onRender" event of a data element. Furthermore, the formatter returns the result so it should be:

this.setDisplayValue(df.format(row["invoicedquantity"]));

But i think it would be easier to create a computed column as datatype "String" in the dataset, with expression:

if(row["unittype"]=="Nos"){
  Formatter.format(row["invoicedquantity"],"#,###.## Kg");
}else{
  Formatter.format(row["invoicedquantity"],"#,### Kg");
}

EDIT: After a deeper look at this, i found a more appropriate way, by changing "numberformat" property. In onRender or onCreate script of the data element (which should be a number datatype), we can do something like:

if(row["unittype"]=="Nos"){
  this.getStyle().numberFormat="#,###.## Kg";
}else{
  this.getStyle().numberFormat="#,### Kg";
}

This is a better approach because the data element has still a numeric datatype, so that if the report is exported in excel it will be recognized by excel as a number.