33

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,

Tim Büthe
  • 62,884
  • 17
  • 92
  • 129
brabster
  • 42,504
  • 27
  • 146
  • 186

5 Answers5

59

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).

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
brabster
  • 42,504
  • 27
  • 146
  • 186
  • 2
    I'd agree with this answer. JSTL should not be concerned with "properly" implementing any logic like rounding. That's a middle tier decision. JSP and JSTL should only be for display. The format tag is the correct thing to do. – duffymo Sep 18 '09 at 09:59
10

I used:

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

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

mm2001
  • 6,427
  • 5
  • 39
  • 37
2

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.

sergionni
  • 13,290
  • 42
  • 132
  • 189
1

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.

Tim Büthe
  • 62,884
  • 17
  • 92
  • 129
1

With the current EL version you can use

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

or

<c:set var="expiry"
value="${Math.floor( (expire.time - now.time) / (60 * 1000) )}"/>
Daniel De León
  • 13,196
  • 5
  • 87
  • 72