How to use Base.Rounding.RoundNearestTiesAway : rounded away from zero in Julia

Viewed 47
1 Answers

Pass rounding mode as an argument to round. By default ties are rounded to even number:

julia> tuple.(x, round.(-4.5:4.5))
10-element Vector{Tuple{Float64, Float64}}:
 (-4.5, -4.0)
 (-3.5, -4.0)
 (-2.5, -2.0)
 (-1.5, -2.0)
 (-0.5, -0.0)
 (0.5, 0.0)
 (1.5, 2.0)
 (2.5, 2.0)
 (3.5, 4.0)
 (4.5, 4.0)

but if you want to round ties away from zero use:

julia> tuple.(x, round.(-4.5:4.5, RoundNearestTiesAway))
10-element Vector{Tuple{Float64, Float64}}:
 (-4.5, -5.0)
 (-3.5, -4.0)
 (-2.5, -3.0)
 (-1.5, -2.0)
 (-0.5, -1.0)
 (0.5, 1.0)
 (1.5, 2.0)
 (2.5, 3.0)
 (3.5, 4.0)
 (4.5, 5.0)

As you can see for 1.5 and -1.5 there is no difference between default rounding mode and the rounding mode you want. But for 2.5 and -2.5 there is a difference.

Related