Can I round 0.1 + 0.2 to 0.30 not the default 0.30000000000000004 in Julia.

It sounds like what you actually want is a number type that can accurately represent fractions. How about a Rational number?

``````julia> 1//10+2//10
3//10

julia> float(1//10+2//10)
0.3
``````

If you know you have exactly fractions I would go with above suggestion.

If you don’t know that and just want to represent numbers with some amount of significant digits you can do

``````julia> round(0.1+0.2, sigdigits=1)
0.3
``````
1 Like

Hey thanks for the reply. But I am not looking for rational numbers as a solution. Is it possible to round the float result to a lesser precision with dynamic decimal digits. Essentially by not using round() digit or sigdigits option,

Hey thanks for the reply. I already tried this method. But in various test cases sigdigits can vary. Can I dynamically assign sigdigits some how?

Can you explain what behaviour you want?

Maybe you need to use a decimal floating point type such as GitHub - JuliaMath/DecFP.jl: Julia IEEE decimal floating-point via the Intel decimal-float library.

2 Likes

You have to define the behavior you want. “Dynamic digits”—based on what?

Just in case, for MATLAB-like formatting see a solution in this post.

In case you are not aware of what is causing this phenomenon, look here: https://0.30000000000000004.com/
and here: PSA: floating-point arithmetic

2 Likes

The problem is that 0.1 with floating points arithmetic is not equal to the real number 0.1, it is only equal if you round it to somewhere between one and n significant digits where n is based on where the difference show up. And since there is a range of valid significant digits to make them equal it is hard to automatically figure out how many you intended to provide, and thus hard to do the calculations with floats and round after in some automated manner.

It sounds like the decimal floating point package mentioned above could be what you are after?