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.

2 Likes

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

2 Likes

Put very simply, it’s because

julia> 10.00
10.0

Check this post for a Matlab-like solution.

**julia>** round(0.79598037, sigdigits=2)

0.8

**julia>** round(0.79598037, sigdigits=3)

0.796

The correct 2-sigdigit answer is “0.80”

I think you’re just confused by how it displays. The round function tries to round it to the closest Float64 value to the one requested, but then has no control over how it is displayed — it is printed in the shortest possible decimal representation, like any other Float64 value.

Moreover, since this is still a binary floating-point value (= integer times power of two), it isn’t possible for it to be an exact decimal value anyway. e.g. the Float64 value 0.8 is actually 0.8000000000000000444089209850062616169452667236328125, which is the closest 53-bit integer × 2ᵏ value to 0.8. (This is just how computer arithmetic works; it’s not specific to Julia.)

If you just want to print something to two significant digits, use @printf or @sprintf from the Printf standard library:

julia> @printf("%0.2f", 0.79598037) # two digits after the decimal point
0.80
julia> @printf("%0.1e", 0.79598037) # two significant digits in scientific notation
8.0e-01
6 Likes

Of course!

The keyword sigdigit of round, referring to decimal digits confused me.

In this context, the OP was asking for a “specific number of /shown/ decimal places”. As said above, this is a problem of displaying strings for the likes of printf, not round for rounding the numeric type.

Though not in Base, Printf is a standard library.