How to calculate the result list numbers in column?

前提是你 提交于 2020-03-05 00:24:59

问题


I'm using SpreadsheetMapper tool, I want to calculate the result listed numbers in a column.

This code is not working when I use the result list.

<#function TW nums...>
  <#local sum = 0>
  <#list nums as num>
    <#local sum += num>
  </#list>
  <#if nums?size != 0>
    <#return sum >
  </#if>
</#function>
${TW(result['TotalWeightListResult']!)}

https://prnt.sc/r3h137

It works when I use static listed numbers.

<#function TW nums...>
  <#local sum = 0>
  <#list nums as num>
    <#local sum += num>
  </#list>
  <#if nums?size != 0>
    <#return sum >
  </#if>
</#function>
${TW(10 20)}

reference - https://freemarker.apache.org/docs/ref_directive_function.html

here is the first thing I'm thinking - How to calculate the listed numbers from the child datastore?


回答1:


If you declare TW with nums... parameter, and you pass a list to TW, it will be just the first element inside nums. That's because parameters have no declared type in FreeMarker, so it's not obvious what you meant.

There's a further confusing coincidence in you example. If you are sending somethingMissing! to TW, then the first element of nums will be an empty string, which is the result of the expression! operation. Because + is overloaded to work both as addition, and as string concatenation, sum += num will no fail, instead, it will do a string concatenation. So first it converts sum to the string "0", and then append the empty string to it. So you end up with return value "0", a string, which when it's printed, looks just like the number 0. But it's not really a 0 number.

So, just use <#function TW nums>, then it will work as expected. In case you want to pass a literal list, you can write TW([10, 20]) then. But I guess typically you don't want to pass a predefined list to TW, and so the extra [] is not a big deal.



来源:https://stackoverflow.com/questions/60261253/how-to-calculate-the-result-list-numbers-in-column

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!