我发现了很多关于如何在 JSTL 中对数字进行四舍五入的问题。我的问题是相反的。不知何故,当我计算胜利/总数以获得胜利的百分比时,我总是得到 0 或 1。模式是一致的:如果胜利 >= 失败,结果为 1,否则为零。所以似乎有一个 Math.round 在这里某处进行。但我不知道它来自哪里。
我一直在尝试重现此错误,但每当我尝试重现它时,我实际上得到了我期望的值(0 到 1之间的值)。这让我认为问题在于我正在执行 SQL 查询,并将列表结果添加到模型中(我使用的是 Spring MVC),尽管我不确定为什么会出现问题。
Spring MVC 控制器代码:
@RequestMapping(value = "/player/{player}", method = RequestMethod.GET)
public String player(@PathVariable String player, Model model) {
String query = "SELECT v2.player, SUM(IF(v1.result >= 26, 1, 0)) `playerWins`, " +
"SUM(IF(v2.result >= 26, 1, 0)) `oppWins` FROM mines_playing AS v1 " +
"JOIN mines_playing AS v2 ON (v1.gameid = v2.gameid) AND (v1.playerpos != v2.playerpos) " +
"JOIN mines AS v3 ON (v1.gameid = v3.gameid) AND v3.finished = 1 " +
"WHERE v1.player = ? AND v3.finished = 1 " +
"GROUP BY v2.player " +
"ORDER BY playerWins DESC";
Session sess = sessionFactory.openSession();
SQLQuery q = sess.createSQLQuery(query);
q.setString(0, player);
q.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
List<?> list = q.list();
model.addAttribute("size", list.size());
model.addAttribute("winList", list);
model.addAttribute("player", player);
sess.disconnect();
return "player/playerstats";
}
JSTL 代码:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
(...)
<c:forEach items="${winList}" var="element">
<c:set var="lost" value="${element['oppWins']}" />
<c:set var="wins" value="${element['playerWins']}" />
<c:set var="total" value="${wins + lost}" />
<c:if test="${total > 0}">
<tr>
<td><a href="<c:url value="vs/${element['player']}" />"><c:out value="${element['player']}">Null</c:out></a></td>
<td>${total}</td>
<td>${wins}</td>
<td>${lost}</td>
<td>${wins / total}</td>
</tr>
</c:if>
</c:forEach>
我究竟做错了什么?为什么wins / total的值会自动四舍五入?