fn:round

Rounds a value to a specified number of decimal places, rounding upwards if two such values are equally near.

Signatures

fn:round($arg as xs:numeric?) as xs:numeric?
fn:round(
    $arg as xs:numeric?, 
    $precision as xs:integer
) as xs:numeric?

Properties

This function is deterministic, context-independent, and focus-independent.

Rules

General rules: see Functions on numeric values.

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 (for example, if the fractional part in $arg is exactly .5), the function returns the one that is closest to positive infinity.

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 single-argument version of this function produces the same result as the two-argument version with $precision=0 (that is, it rounds to a whole number).

When $arg is of type xs:float and xs:double:

  1. If $arg is NaN, positive or negative zero, or positive or negative infinity, then the result is the same as the argument.

  2. For other values, 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 $arg.

Notes

This function is typically used with a non-zero $precision 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(35.425e0, 2). The result is not 35.43, as might be expected, but 35.42. This is because the xs:double written as 35.425e0 has an exact value equal to 35.42499999999..., which is closer to 35.42 than to 35.43.

Examples

The expression fn:round(2.5) returns 3.0.

The expression fn:round(2.4999) returns 2.0.

The expression fn:round(-2.5) returns -2.0. (Not the possible alternative, -3).

The expression fn:round(1.125, 2) returns 1.13.

The expression fn:round(8452, -2) returns 8500.

The expression fn:round(3.1415e0, 2) returns 3.14e0.