Raj Raj - 5 years ago 131
Java Question

format double value to two decimal places in EL expression in jsp

How can I format the double value salary to two decimal places in %{emp.salary}

Code in jsp page below



<input type='text' name='salary' value='<s:property value="%{emp.salary}"/>' />


I know how to do it in servlet/POJO classes and send it correctly. My question is how to do it on the jsp page inside the el expression.

Also I already know it is not the best way . But I want to know if it can be done.

Answer Source

you can use bellow code to number format :

<fmt:formatNumber type="number" maxFractionDigits="2" value="${emp.salary}" />

But if you want to use the s:property any way then this could help.

<s:property value="getText('{0,number,#,##0.00}',{emp.salary})"/>

For curious mind udaybhaskar.

How to find this getText() solution:

frankly speaking I didn't tried to learn them I tried to found a solutoion. For example in this case to format the double number. I knew I need to to use a nested tag.
like:

<s:property value="somethig/ possiblly another tag for format"/>

I find out <s:text> do some text formating. so I go there . In search of something like. <s:property value="<s:text name="?" />"/>

If you go to the bottom you will find out a suggestion (a little one) saying to use getText(). Which actaully a method in ActionSupportclass of struts. ActionSupport

There are many version of getText().

In the <s:text> documentation page it also recommend to see MessageFormat. Because getText() use this MessageFormat to format the text. Now go to MessageFormat and try to understand Patterns and Their Interpretation .

And finally gel them all together.

So once again I dint learn I find out.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download