Search code examples
javajstlbigdecimalabsolute

JSTL: Absolute value of a BigDecimal (Proper way...)


Pardon me for the brain fart tonight but for some reason... this is the best solution I can come up with right now on getting the ABS of a BigDecimal with JSTL right now... No math tricks outside of ABS too. I have to maintain precision.

I know there is a better way to handle it... what's your suggestion? Any google search is pulling up help on formatNumber and handling currencies for the delta/negatives.

<c:forEach items="${arr}" var="cursor" varStatus="itemsRow">
  <c:choose>
    <c:when test="${cursor.value < 0}">
      <td width="75px" align="right">
        <fmt_rt:formatNumber pattern="#,###,###,###.##" value="${cursor.value * -1}" minFractionDigits="2"/></td>
    </c:when>
    <c:otherwise>
      <td width="75px" align="right">
        <fmt_rt:formatNumber pattern="#,###,###,###.##" value="${cursor.value}" minFractionDigits="2"/></td>
    </c:otherwise>
  </c:choose>
</c:forEach>

Solution

  • Use BigDecimal.abs() on the server side; don't do this kind of work in the JSP.

    If you must, wrap it up in a JSP-based custom tag, or create a JSTL function wrapper to handle the abs.

    Also, refactor, similar to this (completely untested), if you can't do the work in an appropriate place:

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <c:forEach items="${arr}" var="cursor" varStatus="itemsRow">
      <c:set name="val" value="${cursor.value < 0 ? cursor.value * -1 : cursor.value}"/>
      <td width="75px" align="right">
        <fmt_rt:formatNumber pattern="#,###,###,###.##" value="${val}" minFractionDigits="2"/>
      </td>
    </c:forEach>