Format javax.money.MonetaryAmount

classic Classic list List threaded Threaded
7 messages Options
Reply | Threaded
Open this post in threaded view
|

Format javax.money.MonetaryAmount

paranoiabla
Hello,

how can I format values of type javax.money.MonetaryAmount? If I simply print them with th:text I get result like this: "USD8.0", but I would like to see "$ 8.0".

Thanks
Reply | Threaded
Open this post in threaded view
|

Re: Format javax.money.MonetaryAmount

Metroids
You would format these the same way you do it in java code... except you would put the formatter on the model, and call it when you use th:text

Controller
String controllerMethod(Map<String, Object> model) {
  model.put("format", MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder.of(Locale.US).setFormatName("SYMBOL").build());
  .
  .
  .

Html
<span th:text="${format.format(amount)}

I'm not really familiar with MonetaryAmount, I just copy the formatter creation code.
Reply | Threaded
Open this post in threaded view
|

Re: Format javax.money.MonetaryAmount

Emanuel
Administrator
In reply to this post by paranoiabla
If you're using Spring, you can configure converters on the conversion service that Thymeleaf will make use of: http://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html#the-conversion-service
Reply | Threaded
Open this post in threaded view
|

Re: Format javax.money.MonetaryAmount

paranoiabla
Hello,

in the spring conversion service there is no converter to convert between Money and String. I tried to create one, registered it in the application context, but it is not added to the default conversion service. Furthermore I tried creating my own conversion service, but I couldn't find a way to tell thymeleaf to use my custom conversion service instead of the default one. So in the end I ended up adding the converter in the model and then using it like this:

${moneyConverter.converter(order.totalDiscounts)}

This looks really ugly and I would love to use the conversion service, but neither spring nor thymeleaf explain how to use a custom conversion service with thymeleaf.
Reply | Threaded
Open this post in threaded view
|

Re: Format javax.money.MonetaryAmount

Emanuel
Administrator
I would have thought the chapter in the Thymeleaf + Spring docs I linked to would have showed how to set up a custom converter.  I've never tried setting one up myself though.
Reply | Threaded
Open this post in threaded view
|

Re: Format javax.money.MonetaryAmount

paranoiabla
I think the problem is really with spring-boot. Spring-boot somehow has autowired a conversion service which thymeleaf is uses. And now if I declare a new one thymeleaf does not respect it.
Reply | Threaded
Open this post in threaded view
|

Re: Format javax.money.MonetaryAmount

Zemi
Administrator
Hello,

maybe this is a silly note but make sure that you're using the double braces syntax, like in

  <span th:text="{{amount}}">$4.8</span>

Regards,
  Zemi