freemarker 中两个数字的除法 - 不正确的结果

Division of two numbers in freemarker - incorrect result

我在 Kotlin 中使用 freemarker 2.3.26。我的模板中有两个变量,我需要将它们分开。

Variable ${a} is Int and its value is 28.
Variable ${b} is Int and its value is 5.
Output of ${a/b} should be 5, but really it is 6. 

我发现这可能是四舍五入造成的

28/5 = 5.6 = rounds to 6

如何正确处理?还有比这更优雅的方式吗?

${(a/b)?floor}

您的 number_format 配置设置必须类似于 '0',因此当数字转换为字符串时 小数点丢失 。我永远不会使用这样的 number_format,因为它很混乱。使用通常的 number_format,例如 '0.####',您会得到 5.6,因为 5 / 6 确实是 5.6,如果您需要对它下限,那么您需要对其进行明确说明。现在,如果您确定要在格式化期间删除小数点(但同样,我认为这是一种危险的做法),请使用 number_format 之类的 '0;;roundingMode=floor' (自 FreeMarker 2.3.24 起),然后${28/5} 将打印 5.

另一个可能更好的解决方案是,如果两个数字都是整数 Java 类型,那么您进行整数除法(如 Java)。这可以通过将 arithmetic_engine 配置设置设置为 conservative 来实现。这通常也不是一个好的做法,因为模板语言没有声明变量的类型,所以 a/b 会做什么并不明显。随着数据模型的发展,您从 BigDecimal 切换到整数 Java 类型,这可能会导致错误的输出。