Rounding solution output in JuMP

When I solve a problem in JuMP, my code ends with

    @show value(m);

and then it prints the solution m to the problem–as directed by the @show value(m) line. But it prints many decimal places of m. I only want 2 or 3 decimal places. How do I get it to give me only the desired number of decimal places?

I know I can use @show value(round(m,digits=3)) but that is annoying to write when I want to print out many variables in the solution since then I have to write the round function many times. Is there a way to just impose the rounding automatically for all variables in the solution?


Not that I know of.

I believe the usual is to save all of them rounded in the same or other data structure. But you need to apply round at least one time.


You may want to save all your values in a data structure as @Henrique_Becker suggested, but to answer your question directly, you can write your own macro:

julia> macro show2(x)
                      print(" = ")
                      println(round($x; digits=2))
@show2 (macro with 1 method)

julia> @show sqrt(3);
sqrt(3) = 1.7320508075688772

julia> @show2 sqrt(3);
sqrt(3) = 1.73
1 Like

That’s great thanks! But how do out save all values to a data structure? I see in the docs it talks about containers
so I could do that, but then I think I would have to rewrite the model functions in terms of a vector (i.e. a container) for the variables.

Is there something where I could do like

data_structure_for_solution_vars =  optimize!(model).solution # ???
@show2 data_structure_for_solution_vars

I’m not sure what’s idiomatic in JuMP, but you could probably do something like

round2(x) = round(x; digits=2);
map(round2∘value, (;x,y,z))

if your parameters are x,y,z.

You can query a vector of all variables with all_variables(model), but this doesn’t preserve the container structure. You’ll need to write something custom.