将尾零格式化为特定小数点的问题



我在使用format-number函数时遇到了一些困难。

给定XML

<testvalues>
<test value="02.25"/>
<test value="02.2"/>
<test value="02.20"/>
</testvalues>

我正在尝试产生这个输出

<testvalues>
<test>02.25</test>
<test>02.2</test>
<test>02.20</test>
</testvalues>

但是我找不到图片串,请这样做。

给定xslt

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="xs"
version="2.0">
<xsl:template match="/">
<xsl:apply-templates/>
</xsl:template>

<xsl:template match="testvalues">
<xsl:copy>
<xsl:apply-templates mode="by-1d"/>
<xsl:apply-templates mode="by-1plus1d"/>
<xsl:apply-templates mode="by-2d"/>
</xsl:copy>
</xsl:template>

<xsl:template match="test" mode="by-1d">
<xsl:copy>
<xsl:value-of select="format-number(@value,'00.0')"/>
</xsl:copy>
</xsl:template>
<xsl:template match="test" mode="by-1plus1d">
<xsl:copy>
<xsl:value-of select="format-number(@value,'00.0#')"/>
</xsl:copy>
</xsl:template>
<xsl:template match="test" mode="by-2d">
<xsl:copy>
<xsl:value-of select="format-number(@value,'00.00')"/>
</xsl:copy>
</xsl:template>

</xsl:stylesheet>

创建的输出是

<?xml version="1.0" encoding="UTF-8"?>
<testvalues>
<test>02.2</test>
<test>02.2</test>
<test>02.2</test>
<test>02.25</test>
<test>02.2</test>
<test>02.2</test>
<test>02.25</test>
<test>02.20</test>
<test>02.20</test>
</testvalues>

后面的零与输入的数字不匹配。

  • '00.00'将强制后面2个数字
  • '00.0'将修剪为一个尾数字
  • '00.0#'将强制使用2位数字,除了其中,当修剪为1位时,第二位数字为零

我想在输入为1位的情况下打印1位尾位,但在输入为>1位的情况下打印2位(包括零)。

这可能吗?

我想在输入为1位的情况下打印1位尾位,但在输入为>1位的情况下打印2位(包括零)。

要使完全,您可以使用:

<xsl:template match="test">
<xsl:copy>
<xsl:value-of select="format-number(@value, if(string-length(substring-after(@value, '.')) > 1) then'00.00' else '00.0')"/>
</xsl:copy>
</xsl:template>

给定输入:

XML>
<testvalues>
<test value="02"/>
<test value="02.2"/>
<test value="02.20"/>
<test value="02.200"/>
<test value="02.2000"/>
<test value="02.20002"/>
</testvalues>

将产生:

结果

<?xml version="1.0" encoding="UTF-8"?>
<testvalues>
<test>02.0</test>
<test>02.2</test>
<test>02.20</test>
<test>02.20</test>
<test>02.20</test>
<test>02.20</test>
</testvalues>

演示:https://xsltfiddle.liberty-development.net/nbBfrFy/2

最新更新