2

I have a JSP with some monetary amounts in £s. I want people viewing the same page from the US to see $ symbol instead of £s. (Forget for a moment that the values ought to be converted as well).

I am using this JSTL solution to set the locale

<c:set var="language" value="${not empty param.language ? param.language : not empty language ? language : pageContext.request.locale}" scope="session" />
<fmt:setLocale value="${language}" />

which works perfectly for output fields like this:

<fmt:formatNumber type="currency" value="${myOutputAmount}" />

but there are also some input fields that have the £ on its own before the input box, e.g.:

£<input type="text" id="myInputAmount"/>

How can I use that locale to show the relevant currency symbol instead of £?

I have searched and found solutions for iPhone, PHP, android, C# and Java. I could implement a Java solution in my JSP but the JSTL one was so neat I'm sure there must be an easy way, tapping into however that works.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
hobbes_child
  • 131
  • 2
  • 12

1 Answers1

1

There is unfortunately no JSTL tag for this.

In plain Java you could get it by Currency#getSymbol() as follows:

String currencySymbol = Currency.getInstance(new Locale(language)).getSymbol();
// ...

You could wrap it around in a Javabean getter, an EL function or maybe a (shudder) scriptlet. You can find a concrete example of how to create an EL function near the bottom of this answer.


Update: you could use this "hack" to get the currency symbol out of a <fmt:formatNumber>:

<fmt:formatNumber var="currencyExample" value="${0}" type="currency" maxFractionDigits="0" />
<c:set var="currencySymbol" value="${fn:replace(currencyExample, '0', '')}" />
...
${currencySymbol}<input type="text" name="amount" />
Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Thanks @BalusC. I went for the EL option. It works, except that: (a) I had to split my JSTL "language" variable into "language" and "country", e.g. "en_US" into "en" and "US" for the Locale constructor; (b) it returns "USD" when I want "$". From what I've read I think this is because of my default locale? I'm looking into it... – hobbes_child Nov 29 '11 at 17:43
  • Perhaps I should have said earlier that my "language" variable comes from my setting `session.setAttribute("language", "en_US");` server-side – hobbes_child Nov 29 '11 at 17:48
  • I see. Well, the "hack" in my updated answer should work out for you. – BalusC Nov 29 '11 at 17:54
  • Indeed it does! I'm happy with that. Thanks, you are a star. – hobbes_child Nov 29 '11 at 17:58