with_rounding(f::Function, T, mode)

Change the rounding mode of floating point type T for the duration of f. It is logically equivalent to:

old = get_rounding(T)
set_rounding(T, mode)
set_rounding(T, old)

See get_rounding for available rounding modes.


In the Julia programming language, the with_rounding function allows you to change the rounding mode of a floating point type T for the duration of a given function f. It follows the logical steps:

  1. Save the current rounding mode of type T using get_rounding(T).
  2. Set the rounding mode of type T to the desired mode using set_rounding(T, mode).
  3. Execute the function f().
  4. Restore the original rounding mode of type T using set_rounding(T, old).

Here are some examples of how to use the with_rounding function:

  1. Round a floating-point operation with different rounding modes:

    julia> x = 1.5;
    julia> with_rounding(RoundDown, Float64) do
              x = x / 2

    In this example, the value of x is divided by 2 using the RoundDown rounding mode.

  2. Calculate the square root with increased precision:

    julia> precision = BigFloat.precision;
    julia> with_rounding(RoundUp, BigFloat) do

    This example calculates the square root of 2 with increased precision using the RoundUp rounding mode.

  3. Perform a custom rounding operation:
    julia> with_rounding(RoundNearest, Float64) do
              round(Int, 3.7)

    Here, the round function is called within the with_rounding context to perform rounding to the nearest integer.

Remember that get_rounding provides available rounding modes for a specific floating point type.

See Also

cmp, float, get_bigfloat_precision, get_rounding, get_zero_subnormals, isapprox, maxintfloat, mod2pi, nextfloat, precision, prevfloat, rationalize, round, set_bigfloat_precision, set_rounding, set_zero_subnormals, significand, with_bigfloat_precision, with_rounding,

User Contributed Notes

Add a Note

The format of note supported is markdown, use triple backtick to start and end a code block.

*Required Field

Checking you are not a robot: