Skip to main content

JSF Tip #14 - The NumberConverter

Posted by mriem on October 2, 2012 at 12:54 PM PDT

How do you use the JSF NumberConverter?

If you are outputting a value, how would you show a currency code along with it?

 <html xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core">
  <h:outputText value="#{user.income}">
   <f:convertNumber currencySymbol="USD" type="currency"/>
  </h:inputText>
</html>

But in all reality would you not expect a currency symbol instead? How would you show that?

 <html xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core">
  <h:outputText value="#{user.income}">
   <f:convertNumber currencySymbol="$" type="currency"/>
  </h:inputText>
</html>

Or you need to show the comma's at the thousands, millions and so on.

 <html xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core">
  <h:outputText value="#{user.income}">
   <f:convertNumber currencySymbol="$" groupingUsed="true" type="currency"/>
  </h:inputText>
</html>

Now changing gears a bit, you want to accept donations. But you want to make sure they can only donate whole numbers.

 <html xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core">
  <h:inputText value="#{user.donation}">
   <f:convertNumber integerOnly="true" type="number"/>
  </h:inputText>
</html>