XSLT 1.0似乎将负半数向上舍入而不是向下(即-2.5到-2)。虽然它可能看起来不那么传统,但我可以将其更改为将其舍入到-3吗?
有没有办法改变这种行为(开发新功能,使用不同的功能,供应参数等),还是我必须使用模板?
我已经编写了自己的模板,但它使得我的XSL比仅包含循环函数时更加混乱。
<xsl:template match="/">
<xsl:value-of select="round(-2.5)"/>
<xsl:call-template name="customRounding">
<xsl:with-param name="input" select="-2.5"/>
</xsl:call-template>
</xsl:template>
<xsl:template name="customRounding">
<xsl:param name="input"/>
<xsl:choose>
<xsl:when test="$input = ''">
<xsl:value-of select="0"/>
</xsl:when>
<xsl:when test="$input < 0">
<xsl:value-of select="round($input * -1) * -1"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="round($input)"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
编辑:我之前曾说过,将负数向上舍入可能被认为比将它们向下舍入更正确。然而,经过更多的阅读,我意识到四舍五入的数字是模糊的,并且惯例各不相同。
答案 0 :(得分:2)
2*($num >= 0) - 1
如果$num
为负数,将给出-1,否则为+1(数字上下文中的布尔表达式为0表示false,1表示true)。鉴于此,您可以round($sign * $num) * $sign
来获得您所追求的结果。不是一个功能,但它可能比模板调用更简洁。
答案 1 :(得分:-1)
您可能更喜欢其他行为:“舍入”数字有三个XPath函数:
floor(n)
- 返回小于 n 的下一个整数。例如:floor(2.9) = 2
ceiling(n)
- 返回大于 n 的下一个整数。例如:ceiling(2.1) = 3
round(n)
- 对数字进行舍入。例如:round(2.5) = 3
,round(2.49999) = 2
,round(-2.5) = -2
,round(-2.50001) = -3
要将-2.5
转换为-3
,请使用floor(-2.5)
。