Vehemon
Vehemon

Reputation: 41

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>

Upvotes: 1

Views: 6401

Answers (2)

Dave Newton
Dave Newton

Reputation: 160291

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>

Upvotes: 2

GreyBeardedGeek
GreyBeardedGeek

Reputation: 30088

Assuming that you're using some sort of MVC framework, or at least have a servlet feeding the data to your JSP, I'd suggest building your list of BigDecimals in the controller / servlet as absolute values - use BigDecimal.abs() - so that you don't have to muck up the JSP with this kind of stuff.

Upvotes: 1

Related Questions