将值四舍五入到小数点后两位

时间:2019-12-10 12:40:36

标签: xml xslt xslt-2.0

我想将十进制值四舍五入到小数点后两位。

输入:

<tab>
  <re>9.47499999/re>
  <re>-6.965111</re>
  <re>4.761</re>
</tab>

输出应为:

<fed>
  <rte>9.48/rte>
  <rte>-6.97</rte>
  <rte>4.76</rte>
</fed>

尝试的代码:

<xsl:choose>
    <xsl:when test="tab/re > 0">
        <xsl:variable name="finround" select="number(format-number(tab/re,'0.000'))"/>
        <xsl:value-of select="concat(concat('+',format-number($finround,'0.00')),'%')"/>
    </xsl:when>
    <xsl:otherwise>
        <xsl:variable name="finroundsec" select="number(format-number(tab/re,'0.000'))"/>
        <xsl:value-of select="concat(format-number($finroundsec,'0.00'),'%')"/>
    </xsl:otherwise>
</xsl:choose>

我得到的结果:

<fed>
  <rte>9.48/rte>
  <rte>-6.96</rte>
  <rte>4.76</rte>
</fed>
  • minus的值不正确。正确答案是-6.97。但是我得到-6.96。我该如何解决?

我正在使用XSLT 2.0

1 个答案:

答案 0 :(得分:0)

  

我想将十进制值四舍五入到小数点后两位。

     

。 。

     

我正在使用XSLT 2.0

这是一种以所需的精度产生舍入的正确而直接的方法

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:xs="http://www.w3.org/2001/XMLSchema">
 <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="re/text()">
    <xsl:sequence select="round-half-to-even(xs:decimal(.), 2)"/>
  </xsl:template>
</xsl:stylesheet>

将此转换应用于提供的XML文档(已更正,格式正确!)

<tab>
    <re>9.47499999</re>
    <re>-6.965111</re>
    <re>4.761</re>
</tab>

产生了所需的正确结果

<tab>
   <re>9.47</re>
   <re>-6.97</re>
   <re>4.76</re>
</tab>

说明

  1. 将文本节点的字符串值转换为xs:decimal -不这样做将转换为xs:double -通常会导致精度下降。

  2. 使用标准XPath 2.0函数 round-half-to-even()