Floating point addition in Julia

I am a bit confused about the floating value addition in Julia. When I try to add two float values in Julia am getting a non rounded value with more precision.

julia> 106.8 + 1.085
107.88499999999999

I want to know if there is a way I can round the result as follows.

julia> 106.8 + 1.085
107.885

I have tested the round(value, digit=N) method to get the above result.

Why is the result not rounded by default and Is there any other way to get the rounded result besides round() function.

Welcome! It’s an artifact of IEEE float point arithmetic, see more: https://0.30000000000000004.com/

2 Likes

Hey thank you for the answer. I understood why it is happening. But is there a way I can round the result other than using a function?

if you’re asking if there’s a way to set global/per environment precision, the answer is no.

Use Fractions or Decimals.jl

2 Likes

Continuing from @Oscar_Smith, …or use GitHub - JuliaMath/FixedPointNumbers.jl: fixed point types for julia or rational numbers (3 // 7). These are all good options, under the right circumstances.

Hey, maybe this post helps: PSA: floating-point arithmetic.

1 Like

You can control the number of digits printed in the REPL, e.g., without loosing precision like this (it will affect printing of all subsequent floats):

julia> using Printf

julia> Base.show(io::IO, f::Float64) = @printf(io, "%.3f", f)

julia> 106.8 + 1.085
107.885
2 Likes