【问题标题】:Accessing JSTL variable in jsp of calculation in JSTL访问JSTL中计算的jsp中的JSTL变量
【发布时间】:2014-08-31 10:44:44
【问题描述】:

在jsp中我有这部分并且工作正常

<c:forEach var="info" items="${infoList}" >
<tr>
    <td>${info.key} </td>
    <td>${info.total}</td>
    <td>${info.delay}</td>
</tr>
</c:forEach>

这里的infoList 来自struts 动作类,它是Info 类的ArrayList

public class Info{
private String key;
private String total;
private String delay

}

现在我需要添加另一个&lt;td&gt;,它将打印计算出的百分比,如 ${info.delay}*100/${info.total},但将精确打印小数点后两位数。

我试过了

${ info.totalDelay*100/info.totalShipment } 

打印百分比但不能限制为 2 位数。在java中我可以使用

NumberFormat formatter = new DecimalFormat("#0.00");

但是我将如何做到这一点,因为在&lt;% %&gt; (jap tag) 我不能使用${}

我可以如何访问&lt;% %&gt; 中的那些变量吗?或者我可以在&lt;c:&gt; 标签中使用formatter .format() 吗

【问题讨论】:

    标签: java jsp jstl el


    【解决方案1】:

    使用 JSTL Format Number

    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
    <fmt:formatNumber type="number" minFractionDigits="2" maxFractionDigits="2" value="${ info.totalDelay*100/info.totalShipment } " />
    

    【讨论】:

    • 比任何解决方案都好。绝对值得++。谢谢。
    【解决方案2】:

    我想通了

    在顶部我这样做了:

    <%
     NumberFormat numberFormat=new DecimalFormat("#.##");
    %>
    

    而我就是这样做的:

    <td>
    <c:set var="tl" value="${info.total}"></c:set>
    <c:set var="dl" value="${info.delay}"></c:set>
    <jsp:useBean id="tl" class="java.lang.String"/> 
    <jsp:useBean id="dl" class="java.lang.String"/> 
    
    <%
         out.println(numberFormat.format(Double.parseDouble(dl)*100/Integer.parseInt(tl)));
    %>
    </td>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多