Re: [xsl] collapsing number ranges

Subject: Re: [xsl] collapsing number ranges
From: Jeni Tennison <jeni@xxxxxxxxxxxxxxxx>
Date: Sun, 29 Aug 2004 22:03:46 +0100
Hi Bruce,

> Any pointers on where to find out more about how to use idiv, mod,
> etc.? I'd like to get a better sense of the basics: the logic that
> explains how the above works (e.g. what's going on with the "div
> 100" that gives me the last two digits, what does mod do, etc.). The
> xpath 2.0 spec isn't all that helpful for me.

These are standard programming operators:

  - div is division. For example "5 div 2" gives 2.5.
  
  - idiv is integer division; both arguments have to be integers and
    the result is truncated (i.e. anything after the decimal point
    gets cut off). For example "5 idiv 2" gives 2. The reason that
    $begin idiv 100 gives you everything but the last two digits of
    $begin is that when you divide by 100, you shift everything two
    digits to the left, so the tens and the units now come after the
    decimal point (e.g. 1086 div 100 = 10.86); truncating that gets
    rid of those last two digits (e.g. 1086 idiv 100 = 10).

  - mod gives you the remainder after division. For example "5 mod 2"
    is 1. The reason that $begin mod 100 gives you only the last two
    digits is that when you divide by 100, the remainder is everything
    on top of the nearest multiple of 100 -- the tens and units. For
    example, 1086 mod 100 is 86 because the nearest multiple of 100 is
    1000, and 1086 - 1000 is 86.

I wouldn't have thought of using idiv and mod to get particular digits
if I hadn't seen David C.'s solution. I would have just used
substring() instead. With substring(), the first argument is the
string, the second the index of the character you want to start with,
and the third the length of the string that you want. So:

  - substring($begin, 1, string-length($begin - 2)) gets you
    everything but the last two digits (characters) of $begin

  - substring($begin, string-length($begin) - 1) gets you the last two
    digits (characters) of $begin

Or, since you're using XSLT 2.0, you could use regexs instead. So:

  - replace($begin, '^(\d*)(\d{2})$', '$1') gets you everything
    but the last two digits of $begin

  - replace($begin, '^(\d*)(\d{2})$', '$2') gets you the last two
    digits of $begin
    
Cheers,

Jeni

---
Jeni Tennison
http://www.jenitennison.com/

Current Thread