Search code examples
jspjstl

Adding two dollars amount in JSTL


My goal is make a variable called

"Dollar Diff" = Value of posting.dollarsInHeader -posting.dollarsReceived)/1000000

Check code below

<c:choose>
    <c:when test="${posting.dollarsInHeader != 0 || posting.dollarsReceived != 0}">
        <td class="alignright" class="${posting.dollarsInHeader < 0 || posting.dollarsReceived < 0 ? 'fontRed' : ''}">
            <fmt:formatNumber type="currency" minFractionDigits="1"
                                            maxFractionDigits="1">${(posting.dollarsInHeader - posting.dollarsReceived)/1000000}
        </td>
    </c:when>
    <c:otherwise>
        <td style="text-align: right; padding-right: 10px;">-</td>
    </c:otherwise>
</c:choose>

Instead of ${(posting.dollarsInHeader - posting.dollarsReceived)/1000000}, I want to write ${dollarDiff}


Solution

  • I wouldn't recommend such logic written in view layer (jsp). You can add a field in your posting class and write return the value accordingly.

    //Ommit Posting class declaration
    public double getDollarDiff(){
        return (this.dollarsInHeader-this.dollarsReceived)/1000000;
    }
    

    Then simply reference it with:

    ${posting.dollarDiff}
    

    EL treat your method as a field if it follow getter convention.

    However, if you don't want to modify your pojo, you could try use

    <c:set scope="request" var="dollarDiff" value="${(posting.dollarsInHeader - posting.dollarsReceived)/1000000}"></c:set>
    

    Then reference it with:

    <c:out value="${requestScope.dollarDiff}"></c:out> 
    <!--or-->
    ${requestScope.dollarDiff}