這可以在單個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