How do I round a number in JSTL?

2019-02-02 20:50发布

I'm doing a division in a JSP and I'd like to round the result - how should I do this?

i.e.

<c:set
  var="expiry"
  value="${(expire.time - now.time) / (60 * 1000)}"/>

...how do I round the result?

Thanks,

4条回答
倾城 Initia
2楼-- · 2019-02-02 21:29

As an alternative:

<fmt:formatNumber var="expiry"
  value="${(expire.time - now.time) / (60 * 1000)}"
  maxFractionDigits="0" />

This way you do not lose localization (commas and dots).

查看更多
混吃等死
3楼-- · 2019-02-02 21:40

I used:

${fn:substringBefore(expiry, '.')}

which truncates rather than rounding, but that may be good enough.

查看更多
Anthone
4楼-- · 2019-02-02 21:40

It may looks like:

<c:set var="expire" value="100"/>
<c:set var="now" value="3"/>

<c:choose>
 <c:when test="${(expire mod now)!=0}">
  <c:set var="res" value="${(expire - (expire mod now))/now}"/>
  ${res}
 </c:when>
 <c:otherwise>
  <c:set var="res" value="${expire/now}"/>
  ${res}
 </c:otherwise>
</c:choose>

note: i think you should use mod anyway or % functionality of jstl,i use mod in example. Test,please, "expire" and "now" variables with different values, should work ok.

查看更多
该账号已被封号
5楼-- · 2019-02-02 21:47

What about this dirty hack:

<c:set
  var="expiry"
  value="${(((expire.time - now.time) / (60 * 1000) * 100) - 0.5) / 100.0}"/>

But I would do this in a bean and just show the result here. Beside this, you can define functions in your tld or, if that is not supported in your environment get functions in the expression language by implementing a Map and (ab)use it. You implement the get(Object) method to do what you want and call it like this:

<c:set
  var="expiry"
  value="${Helpers.round[(expire.time - now.time) / (60 * 1000)]"/>

Note, Helpers provides a "getRound()" method which returns your Map implementation.

查看更多
登录 后发表回答