Reputation: 3444
I'm working on a J2EE application which uses Struts (v1) and I would like to format a value being displayed in a JSP. The value to be displayed is a 7 or 8 digit integer and I would like to insert dashes into it, like so:
1234567 -> 1-234-567
12345678 -> 12-345-678
What is the best way to go about this? My first thought was to write a special getter in my form bean which would return the specially formatted String, rather than the Integer. That, of course, seems very smelly - I don't want to add methods to my beans just to format things in my JSP.
Another option I considered was to use bean:write's format attribute. Unfortunately, I can find lots of documentation on how to use format when you're trying to format a date, but I just can't seem to find the correct syntax for working with arbitrary values.
Any thoughts?
Upvotes: 2
Views: 5369
Reputation: 40160
I did some researching on fmt:formatNumber
... I think using -
is causing some weird problem because ,
is the only safe grouping separator. Based on the documentation, it seems like you can comment special character using single quotes, but I don't think it applies in your case.
So, here's my workaround:-
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<c:set var="foo" value="12345678"/>
<fmt:formatNumber value="${foo}" pattern="00,00,000" var="result"/>
${fn:replace(result, ",", "-")}
This works for me. Basically, I use commas instead of dashes, then use the replace function to convert it back to dashes... not quite an elegant solution.
Upvotes: 3
Reputation: 7
use something along these lines, it should help you out!!:
<bean:write name="formBean" property="dashedNum" format="###'-'###'-'###"/>
Upvotes: -1
Reputation: 2294
With bean:write, you can only use DateFormat and DecimalFormat, which can't do what you're looking to do here (DecimalFormat doesn't do totally free form formatting and reserves the - as a special character).
The Struts docs recommend just formatting it in your ActionForm: http://struts.apache.org/1.x/struts-taglib/faq.html#tags
If you really, really want to do it in your JSP, you'll probably have to write your own tag library to handle it. Not even the JSTL can really even handle this for you: http://download.oracle.com/docs/cd/E17802_01/products/products/jsp/jstl/1.1/docs/tlddocs/fmt/tld-summary.html
Upvotes: 1
Reputation: 3827
Use NumberFormat to format numbers.
API : http://download.oracle.com/javase/6/docs/api/java/text/NumberFormat.html
Example:
http://www.kodejava.org/examples/102.html
Upvotes: 0