Round a float, and force a specific number of decimal places

Rounding a float to two decimal places, say, does not necessarily create a number with two decimal places. For example

round(10.001, digits = 2)

produces 10.0

How can I force a specific number of shown decimal places?

1 Like

What is displayed and what it is rounded to is not the same thing, similar to your example we also have

julia> round(10.1, sigdigits=2)
10.0

where it is correctly rounded to two significant digits, but since the following decimals are zero it is still displayed in standard float format with a single decimal zero to signify that it is a float with an integer value (I guess that is the reason at least).

So if you want to change the way that is shown as a result I guess you have to override the show method for floats.

If you just want to print it in a specific way you could have a look at @printf, see e.g.

4 Likes

Just adding that @printf is in the Printf module from standard library, so using Printf is needed. Also @sprintf is useful to get a string with formatted output.

1 Like

Format.jl and Formatting.jl are alternatives to Printf with a more modern formatting language.

1 Like

Put very simply, it’s because

julia> 10.00
10.0

Check this post for a Matlab-like solution.