XSL格式化数字不进行四舍五入

4

在XSL中是否有类似于format-number的东西,可以将数字格式化为'#0.00'的形式而不进行四舍五入?

因此,

  • 5会变成5.00
  • 14.6会变成14.60
  • 1.375会变成1.37

仅使用format-number无法实现此功能,因为它会将1.375四舍五入为1.38

<xsl:value-of select="format-number(MY_NUMBER, '#0.00')" />

这个字符串拼接子串的方法在数字5上不起作用(因为没有“.”),并且也不会在14.6末尾添加零。

<xsl:value-of select="concat(substring-before(MY_NUMBER,'.'), '.',  substring(substring-after(MY_NUMBER,'.'),1,2))" />
我需要做一些繁琐的事情吗:
<xsl:choose>
    <xsl:when test=""></xsl:when>
    <xsl:otherwise></xsl:otherwise>
</xsl:choose>

非常感谢你提前的帮助!

1个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
10

我假设您受限于XSLT 1,因此可以采用类似以下的方法:

<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">


<xsl:template match="/">
:
<xsl:call-template name="f">
<xsl:with-param name="n" select="5"/>
</xsl:call-template>
:
<xsl:call-template name="f">
<xsl:with-param name="n" select="14.6"/>
</xsl:call-template>
:
<xsl:call-template name="f">
<xsl:with-param name="n" select="1.375"/>
</xsl:call-template>
:
<xsl:call-template name="f">
<xsl:with-param name="n" select="-12.1234"/>
</xsl:call-template>
:
</xsl:template>

<xsl:template name="f">
<xsl:param name="n"/>
<xsl:value-of select="format-number(floor($n*1000) div 1000, '#0.00')"/>
</xsl:template>

</xsl:stylesheet>

生产

:
5.00
:
14.60
:
1.38
:
-12.12
:

完美!不确定那个额外的<xsl:value-of select="<xsl:value-of是怎么来的,所以我把它删除了,以免让任何人感到困惑。 - sigmapi13
@sigmapi13 好的,我也从这里删除了。请注意,如果是这种情况,以下句子也需要删除。 - David Carlisle
如果存在负数,David Carlisle 提供的解决方案并不完全适用。 想象以下数字:12.1234-12.123412。如果在 David 提供的 xslt 中使用,结果将是 12.12-12.1312.00。因此,包含负数的双精度实际上会四舍五入。为了防止这种情况发生,需要乘以一千(floor($n*1000) div 1000, ....)。@DavidCarlisle,供您参考。 - Serhat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,