Read XSLT 2.0 and XPath 2.0 Programmer's Reference, 4th Edition Online
Authors: Michael Kay
The conversion to an
xs:double
uses the casting rules (described in Chapter 11), not the rules of the
number()
function. This means that if the value isn't a valid number, the expression will fail with a runtime error, rather than returning the value
NaN
.
5.
If the operands are now of an acceptable type for the operator, the calculation is carried out. In the case of numeric operands, all combinations of numeric values are acceptable, and the values are first promoted to a common type as described in the section
Type Promotion
above. The only other kinds of operands that are acceptable are certain combinations of dates, times, and durations, which are described in the section
Arithmetic using Durations
below. The calculation may succeed or fail (the most obvious example of a failure is division by zero); if it fails, a runtime error is reported.
6.
If the operands are of the wrong type, then a type error is raised. For example, this will happen if one of the operands is an
xs:boolean
or
xs:string
value.
There are two differences to these rules when backward compatibility is in force. Firstly, in step 3, instead of reporting an error when there is more than one item in the sequence, all items except the first are discarded. Secondly, after step 4, any operand of type
xs:untypedAtomic
,
xs:string
,
xs:boolean
,
xs:decimal
(including
xs:integer
), or
xs:float
is converted to an
xs:double
value, using the
number()
function. This means that the result will also be of type
xs:double
. If the value of an operand can't be converted, the answer comes out as
NaN
rather than an error. This rule is written in such a way that arithmetic on dates, times, and durations is unaffected by backward-compatibility modeāit follows the normal 2.0 rules.
Arithmetic Using Numbers
This section describes some of the corner cases that can arise when doing numeric arithmetic.
Integer Arithmetic
With integer operands, there are few surprises.
The result of dividing two integers using the
div
operator is an
xs:decimal
value, but the spec doesn't say what the precision of the result should be. For example, if you write
10
div
3
, then one system might produce the answer
3.333
, while another produces
3.3333333333333333
.