luni, 30 noiembrie 2015

[OmniFaces utilities 2.0] Format the given number as currency with the given symbol


[OmniFaces utilities] The formatCurrency() function format the given number as currency with the given symbol. This is useful when you want to format numbers as currency in for example the title attribute of an UI component, or the itemLabel attribute of select item, or wherever you can't use the <f:convertNumber> tag. The format locale will be set to the one as obtained by Faces#getLocale().

Function:
See also: Faces#getLocale()
Usage:

Let's suppose that we have a map that contains several JSF books names and their prices as floats, as below:

// in real cases, you may hit a database
private final Map<Float, String> booksMap
        = Collections.unmodifiableMap(new HashMap<Float, String>() {
 {
  put(27.76f, "Mastering JavaServer Faces 2.2");
  put(37.20f, "Mastering OmniFaces");
  put(33.78f, "JavaServer Faces 2.2");
  put(29.44f, "JavaServer Faces 2.0, The Complete Reference");
  put(38.68f, "Pro JSF and HTML5");
 }
});

public Map<Float, String> getBooksMap() {
 return booksMap;
}  

Now, we can display a table containing these books names and prices. The prices are formatted via of:formatCurrency() using $ symbol:

<h:dataTable value="#{bookBean.booksMap.entrySet()}" var="book">
 <h:column>
  <f:facet name="header">Book</f:facet>
  #{book.value}
 </h:column>
 <h:column>
  <f:facet name="header">Price</f:facet>
  #{of:formatCurrency(book.key, "$")}
 </h:column>
</h:dataTable>

Niciun comentariu:

Trimiteți un comentariu