Stian
Stian

Reputation: 409

Formatting a double in JSF

I have a problem similar to the one found here : JSF selectItem label formatting.

What I want to do is to accept a double as a value for my and display it with two decimals. Can this be done in an easy way?

I've tried using but that seems to be applied on the value from the inputText that is sent to the server and not on the initial value in the input field.

My code so far:

<h:inputText id="december" value="#{budgetMB.december}" onchange="setDirty()" styleClass="StandardBlack">
    <f:convertNumber maxFractionDigits="2" groupingUsed="false" />
</h:inputText>

EDIT: The above code actually works. I was fooled by JDeveloper that didn't update the jsp page even when I did a explicit rebuild of my project and restarted the embedded OC4J server. However, after a reboot of my computer everything was fine.

Upvotes: 11

Views: 36965

Answers (3)

Mosty Mostacho
Mosty Mostacho

Reputation: 43434

It seems you're actually formatting a currency. There already exists a specific formatter to handle currencies that you can assign many options to:

<f:convertNumber type="currency" />

Some interesting attributes of this tag are: locale, currencyCode, integerOnly, currencySymbol and pattern.

Upvotes: 0

Ian McLaird
Ian McLaird

Reputation: 5585

If what you are trying to do is make the value of the input text field change on screen (to correct user input), you should probably look into using one of the JSF ajax frameworks like Rich Faces.

A possible example would look like this:

<h:inputText id="december" value="#{budgetMB.december}" styleClass="StandardBlack">
  <f:convertNumber maxFractionDigits="2" groupingUsed="false" />
  <a4j:support event="onblur" reRender="december" />
</h:inputText>

I haven't tested this, but I think it may work.

Upvotes: 1

Grant Wagner
Grant Wagner

Reputation: 25931

If I'm not misunderstanding your requirement, I was able to achieve formatting of the value in the input box during the rendering of the view with:

<h:inputText id="text1" value="#{...}">
    <f:convertNumber pattern="#,###,##0.00"/>
</h:inputText>

I was using the Standard Faces Components in my vendor-branded Eclipse so I'm assuming the pattern attribute is part of standard JSF.

Upvotes: 15

Related Questions