[XSL-LIST Mailing List Archive Home] [By Thread] [By Date] [Recent Entries] [Reply To This Message]

Re: XPath / XSLT 2.1 - Rounding algorithms

Subject: Re: XPath / XSLT 2.1 - Rounding algorithms
From: "G. Ken Holman" <gkholman@xxxxxxxxxxxxxxxxxxxx>
Date: Thu, 13 Nov 2008 18:00:31 -0500
Re:  XPath / XSLT 2.1 - Rounding algorithms
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="http://www.w3.org/1999/XSL/Transform"
                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:    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


Purchasing Stylus Studio from our online shop is Easy, Secure and Value Priced!

Buy Stylus Studio Now

Download The World's Best XML IDE!

Accelerate XML development with our award-winning XML IDE - Download a free trial today!

Don't miss another message! Subscribe to this list today.
First Name
Last Name
Subscribe in XML format
RSS 2.0
Atom 0.3
Site Map | Privacy Policy | Terms of Use | Trademarks
Free Stylus Studio XML Training:
W3C Member
Stylus Studio® and DataDirect XQuery ™are products from DataDirect Technologies, is a registered trademark of Progress Software Corporation, in the U.S. and other countries. © 2004-2013 All Rights Reserved.