这可以在单个XPath表达式中完成。
使用:
floor(.) + round(10*(. -floor(.))) div 10
验证使用XSLT作为主机的XPath的:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="text()[contains(.,'.')]">
<xsl:value-of select=
"floor(.) + round(10*(. -floor(.))) div 10"/>
</xsl:template>
</xsl:stylesheet>
当这种转变是在下面的XML文档应用:
<t>
<n>12.5</n>
<n>100.123</n>
<n>5.26445</n>
</t>
的希望,正确的结果产生:
<t>
<n>12.5</n>
<n>100.1</n>
<n>5.3</n>
</t>
说明:标准XPath函数floor()
,round()
使用和XPath的操作div
和你的逻辑。
广义表达:
floor(.) + round($vFactor*(. -floor(.))) div $vFactor
其中$vFactor
是10^N
,其中N
是数字我们想要的小数点后的位数。
利用该表达式,修改后的XSLT转换,这是:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:param name="pPrecision" select="4"/>
<xsl:variable name="vFactor" select=
"substring('10000000000000000000000',
1, $pPrecision+1
)
"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="text()[contains(.,'.')]">
<xsl:value-of select=
"floor(.) + round($vFactor*(. -floor(.))) div $vFactor"/>
</xsl:template>
</xsl:stylesheet>
当该变换是在相同的XML文档(上文),我们生产的$pPrecision
任何有意义的值的有用输出施加。在上面的例子中它被设置为4
和结果中包含所有数字四舍五入至小数点后四位:
<t>
<n>12.5</n>
<n>100.123</n>
<n>5.2645</n>
</t>
显示一些代码,也许我们将有上下文来帮助更好一点。 –
XSLT 2.0是您的选择吗?你可以使用'format-number()'和'xsl:decimal-format'。 –
@Don - 目前没有任何相关的代码。我正在考虑上面提到的3个选择。 @empo - 我需要看看XStream是否支持XSLT 2.0;如果是这种情况,那可能会有所帮助。 – f1dave