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
number.

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


http://www.w3.org/TR/2007/REC-xpath-functions-20070123/#func-round

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="http://www.w3.org/1999/XSL/Transform";
                xmlns:xsd="http://www.w3.org/2001/XMLSchema";
                xmlns:c="urn:X-Crane"
                exclude-result-prefixes="xsd c"
                version="2.0">

<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:template>

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

</xsl:stylesheet>
T:\ftemp>xslt2 peter.xsl peter.xsl con

-2.5: -3
2.5:  3
T:\ftemp>

--
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:    http://www.youtube.com/watch?v=PrNjJCh7Ppg
Video course overview:  http://www.youtube.com/watch?v=VTiodiij6gE
G. Ken Holman                 mailto:gkholman@xxxxxxxxxxxxxxxxxxxx
Crane Softwrights Ltd.          http://www.CraneSoftwrights.com/s/
Male Cancer Awareness Nov'07  http://www.CraneSoftwrights.com/s/bc
Legal business disclaimers:  http://www.CraneSoftwrights.com/legal

Current Thread