3

I have a JSF 1.2 view which is kind of a report generator. Users can select a query, configure some values, then the database is requested and data collected. After that the data can be viewed in a dataTable and finally is exported to Excel. Works fine so far.

Depending on the query the columns have different types, one of which is Double. The Double values should be rounded now...

Since there are many rows (tens or hundreds of thousands) I collect all data as String to avoid time consuming type conversions. That's pretty ok because for the export to Excel I need Strings, too (written to Office XML).

But now the rounding comes in. In the dataTable the doubles shall be rounded. If I had a Double I could easily use f:convertNumber, but I don't have.

My idea would be a String converter which analyzes if it is a numeric value and then formats the String. (Performace is not so critical because there are only 30 or so records in the paged dataTable). How would I accomplish this?

Any (other) suggestions? Thanks!
Mark

Edit:
solved for now with

  public class ReportStringConverter implements Converter {

  DecimalFormat f = new DecimalFormat("#0.00");  

  public Object getAsObject(FacesContext context, UIComponent component, String value)        {
    return value;
  }

  public String getAsString(FacesContext context, UIComponent component, Object value) {
    if (isNumeric(value.toString())) {
      return f.format(Double.parseDouble(value.toString()));
    } else {
      return value.toString();
    }
  }

  private boolean isNumeric(String s) {
    try {
      double d = Double.parseDouble(s);
    } catch (NumberFormatException e) {
      return false;
    }
    return true;
  }

}
  • 1
    just us custom converter , inside it check if the string is a number (something like this http://stackoverflow.com/q/1102891/617373) and if its a number round it... – Daniel Sep 11 '12 at 08:06
  • You are welcome... `"My idea"` ? ;) – Daniel Sep 11 '12 at 15:30

1 Answers1

2

You could use expression language to convert a string to a number by adding 0 to it (example: #{'35.75' + 0}). This allows you to simply use f:convertNumber.

<h:outputText value="#{'35.75' + 0}">
  <f:convertNumber pattern="0"/>
</h:outputText>
Jasper de Vries
  • 19,370
  • 6
  • 64
  • 102