Rounds a value to a specified number of decimal places, rounding to make the last digit even if two such values are equally near.
fn:round-half-to-even
( $arg
as xs:numeric?
xs:numeric?
fn:round-half-to-even
( $arg
as xs:numeric?
,$precision
as xs:integer
xs:numeric?
General rules: see .
The function returns the nearest (that is, numerically closest) value to
$arg
that is a multiple of ten to the power of minus
$precision
. If two such values are equally near (e.g. if the fractional
part in $arg
is exactly .500...), the function returns the one whose least
significant digit is even.
For the four types xs:float
,
xs:double
, xs:decimal
and xs:integer
, it is
guaranteed that if the type of $arg
is an instance of type T then
the result will also be an instance of T. The result may
also be an instance of a type derived from one of these four by restriction. For example, if
$arg
is an instance of xs:decimal
and $precision
is less than one, then the result may
be an instance of xs:integer
.
The first signature of this function produces the same result as the second signature
with $precision=0
.
For arguments of type xs:float
and xs:double
:
If the argument is NaN
, positive or negative zero, or positive or
negative infinity, then the result is the same as the argument.
In all other cases, the argument is cast to xs:decimal
using an
implementation of xs:decimal that imposes no limits on the number of digits that
can be represented. The function is applied to this xs:decimal
value,
and the resulting xs:decimal
is cast back to xs:float
or
xs:double
as appropriate to form the function result. If the
resulting xs:decimal
value is zero, then positive or negative zero is
returned according to the sign of the original argument.
The expression fn:round-half-to-even(0.5)
returns 0.0
.
The expression fn:round-half-to-even(1.5)
returns 2.0
.
The expression fn:round-half-to-even(2.5)
returns 2.0
.
The expression fn:round-half-to-even(3.567812e+3, 2)
returns 3567.81e0
.
The expression fn:round-half-to-even(4.7564e-3, 2)
returns 0.0e0
.
The expression fn:round-half-to-even(35612.25, -2)
returns 35600
.
This function is typically used in financial applications where the argument is of type
xs:decimal
. For arguments of type xs:float
and
xs:double
the results may be counter-intuitive. For example, consider
round-half-to-even(xs:float(150.015), 2)
. The result is not 150.02 as
might be expected, but 150.01. This is because the conversion of the
xs:float
value represented by the literal 150.015 to an
xs:decimal
produces the xs:decimal
value 150.014999389...,
which is closer to 150.01 than to 150.02.