4

How to round number in xslt 2.0

So for example it will work like this:

1.4367 => 1.44
1.3218 => 1.32
VextoR
  • 5,087
  • 22
  • 74
  • 109

3 Answers3

3

Try using the round function:

<xsl:value-of select="round(NUMBER_TO_ROUND*100) div 100"/>
Choppin Broccoli
  • 3,048
  • 2
  • 21
  • 28
  • 1
    You might also like to look at round-half-to-even(), which does "banker's rounding" and allows you to specify the number of decimal places. – Michael Kay Nov 28 '13 at 23:12
1

You are probably looking for format-number() function.

Also in In XSLT 2.0/XPath 2.0 one can use the xs:decimal type to work without loss of precision.

Something like this:

<xsl:stylesheet version="2.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:xs="http://www.w3.org/2001/XMLSchema"
                exclude-result-prefixes="xs">
  <xsl:output omit-xml-declaration="yes" indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="/*">
    <MyTable>
      <xsl:value-of select="xs:decimal(MyValue)"/>
    </MyTable>
  </xsl:template>
</xsl:stylesheet>
Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
1

You may use format-number(). A possible way to use is as below:

<xsl:value-of select="format-number(1.45632,'#.00')"/>

Note: if you don't want 00 to be there, in case no decimal digit is present then use '#.##' instead.

Pierre.Vriens
  • 2,117
  • 75
  • 29
  • 42
  • 1
    **WARNING** The `format-number()`function does "banker's rounding" - same as the `round-half-to-even()` function. `` will return `0.02` instead of the `0.03` expected from standard rounding. – michael.hor257k Aug 28 '21 at 11:47