with_rounding
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)
f()
set_rounding(T, old)
See get_rounding
for available rounding modes.
Examples
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:
 Save the current rounding mode of type
T
usingget_rounding(T)
.  Set the rounding mode of type
T
to the desiredmode
usingset_rounding(T, mode)
.  Execute the function
f()
.  Restore the original rounding mode of type
T
usingset_rounding(T, old)
.
Here are some examples of how to use the with_rounding
function:

Round a floatingpoint operation with different rounding modes:
julia> x = 1.5; julia> with_rounding(RoundDown, Float64) do x = x / 2 end 0.75
In this example, the value of
x
is divided by 2 using theRoundDown
rounding mode. 
Calculate the square root with increased precision:
julia> precision = BigFloat.precision; julia> with_rounding(RoundUp, BigFloat) do sqrt(BigFloat(2)) end 1.414213562373095048801688724209698078569671875376948073176679737990732478462107038850387534327641573
This example calculates the square root of 2 with increased precision using the
RoundUp
rounding mode.  Perform a custom rounding operation:
julia> with_rounding(RoundNearest, Float64) do round(Int, 3.7) end 4
Here, the
round
function is called within thewith_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.