Comparing Numeric Values

Two numeric values can be compared using the general comparison operators: =, !=, <, <=, >, and >=. Values of different numeric types can be compared; one is promoted to the other's type. Nodes that contain numeric values can also be compared using these operators; in that case, they are atomized to extract their typed values. Table 16-2 shows some examples of comparing numeric values.

Some caution should be used when comparing untyped values using the general comparison operators. When an untyped value is compared to a numeric value (for example, a numeric literal), it is cast to the numeric type. However, when two untyped values are compared, they are treated like strings. This means that, for example, the untyped value 100 would evaluate to less than the value 99. If you want to compare two untyped values, you must explicitly cast the value(s) to a numeric type, as shown in the fourth example in Table 16-2.

Table 16-2. Comparing numeric values a

Example

Value

[a]

doc("prices.xml")//prod[3]/discount > 10

false

doc("prices.xml")//prod[3]/discount gt 10

Type error

doc("prices.xml")//prod[3]/discount > doc("prices.xml")//prod[1]/discount

true (it is comparing the string 3.99 to the string 10.00)

doc("prices.xml")//prod[3]/number(discount) >

doc("prices.xml")//prod[1]/number(discount)

false (it is comparing the number 3.99 to the number 10.00)

3 gt 2

true

1 = 1.0

true

xs:float("NaN") = xs:float("NaN")

false

xs:string(xs:float("NaN")) = "NaN"

true

[a] This table assumes that prices.xml is untyped, i.e., has not been validated with a schema.

Numeric values can also be compared using the value comparison operators: eq, ne, lt, le, gt, and ge. However, the value comparison operators treat every untyped operand like a string, even if the other operand is numeric. This means that if you want a numeric comparison, you have to say so, by using an explicit cast.

The value INF (positive infinity) is greater than all other values, and -INF (negative infinity) is less than all other values, but each equals itself. The value NaN cannot usefully be compared with any other value (including itself) using comparison operators, because the result of the comparison operation is always false (unless the operator is !=, in which case it's always true). To determine whether a value is NaN, you can compare its string value to the string NaN, as in string($myVal) = "NaN". In some functions, such as the distinct-values function, NaN is considered to be equal to itself.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.105.255