Re: [xsl] XPath / XSLT 2.1 - Rounding algorithms

Subject: Re: [xsl] XPath / XSLT 2.1 - Rounding algorithms
From: "G. Ken Holman" <gkholman@xxxxxxxxxxxxxxxxxxxx>
Date: Thu, 13 Nov 2008 18:00:31 -0500
At 2008-11-13 16:57 -0500, Rushforth, Peter wrote:
A couple of years ago, I ran into a need to call extension functions
to round numbers in the "traditional" way: to round half up for results of
.5 (or more). I found that it was only possible with XSLT to round to the even

Not sure where you read that ... the round() function goes to the nearest whole number or does a ceiling() for the value "x.5":

Specifically, round-half-up(decimal_num,num_digits), where 'up' means towards
positive or negative infinity, is what I'm looking for.

Except for the number of digits you could do:

if( x < 0 ) then -( round(abs(x)) ) else round(x)

... and use format-number() to handle the digits bit.

I hope the example below helps.

. . . . . . . . . Ken

T:\ftemp>type peter.xsl
<?xml version="1.0" encoding="US-ASCII"?>
<xsl:stylesheet xmlns:xsl="";
                exclude-result-prefixes="xsd c"

<xsl:output method="text"/>

<xsl:template match="/">
-2.5: <xsl:value-of select="c:PeterRound(-2.5)"/>
2.5:  <xsl:value-of select="c:PeterRound(2.5)"/>

<xsl:function name="c:PeterRound">
  <xsl:param name="x"/>
  <xsl:sequence select="if( $x &lt; 0 ) then -( round(abs($x)) )
                                        else round($x)"/>

T:\ftemp>xslt2 peter.xsl peter.xsl con

-2.5: -3
2.5:  3

Upcoming XSLT/XSL-FO hands-on courses:      Wellington, NZ 2009-01
Training tools: Comprehensive interactive XSLT/XPath 1.0/2.0 video
Video sample lesson:
Video course overview:
G. Ken Holman                 mailto:gkholman@xxxxxxxxxxxxxxxxxxxx
Crane Softwrights Ltd.
Male Cancer Awareness Nov'07
Legal business disclaimers:

Current Thread