简体   繁体   中英

grails gsp g:set counter problem

I'm trying to sum up a set of values using the g:set example from the Grails 1.3.7 docs but it looks like g:set is treating the integers as strings.

With values for ${grossScore.score} of [ 5, 5, 4, 4 ] instead of the total being 18, the total is 5544.

<g:set var="totalScore" value="0"/>
<g:each var="grossScore" in="${Score.findAllByScorecard(cardGross)}">
    <g:set var="totalScore" value="${totalScore + grossScore.score}"/>
</g:each>

Another option is to ensure that totalScore is an integer, like this:

<g:set var="totalScore" value="${0}"/>

I believe this will force totalScore to be an Integer, so you won't have to worry about concatenation instead of addition.

If you KNOW that the grossScore.score value is an integer, you can probably just swap the two in your addition:

<g:set var="totalScore" value="${grossScore.score + totalScore}"/>

Usually, the left-hand of an operation determines the type of operation, assuming such exists. Since you have totalScore on the left, and it's just an Object (default for ag:set), the default Object.plus() operation is used, which is very similar to String.

If you make grossScore.score the left hand side, then it should try to use Integer.plus(), which should give you what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM