Print vs @printf

Hello,
Is it possible to write the following program using print, round and digits instead of using @printf?

using Printf
# needed in order to use @printf
function tickets()
   print("Price of reserved ticket? ")
   rPrice = parse(Float64, readline())
   print("Number sold? ")
   rTickets = parse(Int, readline())
   rSales = rPrice * rTickets
   print("Price of stands ticket? ")
   sPrice = parse(Float64, readline())
   print("Number sold? ")
   sTickets = parse(Int, readline())
   sSales = sPrice * sTickets
   print("Price of grounds ticket? ")
   gPrice = parse(Float64, readline())
   print("Number sold? ")
   gTickets = parse(Int, readline())
   gSales = gPrice * gTickets
   tTickets = rTickets + sTickets + gTickets
   tSales = rSales + sSales + gSales
   @printf("\nReserved sales: \$%0.2f\n", rSales)
   @printf("Stands sales: \$%0.2f\n", sSales)
   @printf("Grounds sales: \$%0.2f\n", gSales)
   @printf("\nTotal tickets sold: %d\n", tTickets)
   @printf("Total money collected: \$%0.2f\n", tSales)
end
tickets()

This is an example from the book Julia - Bit by Bit: Programming for Beginners. In this book, the author says:

As explained earlier, we use @printf (rather than print ) to ensure the dollar amounts are always printed to two decimal places.

Thank you.

One simple example:

rSales = 1414.217

using Printf
@printf("\nReserved sales: \$%0.2f\n", rSales)

print("\nReserved sales: \$$(round(rSales, digits=2))\n")
2 Likes

While as @rafael.guerra shows, the answer is yes, if you don’t like the @printf syntax, I would suggest using Format.jl instead of basically implementing it yourself (though this can of course be useful to learn the language).

julia> using Format

julia> rSales = 1414.217;

julia> println("\nReserved sales: $(format(rSales, precision=2))")  # (Note: format outputs a String)

Reserved sales: 1414.22

In this case it is not easier than just rounding, but it is more flexible. E.g. if you want to add a thousands separator ,, you can simply use

julia> println("\nReserved sales: $(format(rSales, precision=2, commas=true))")  # (Note: only comma as thousands separator is supported)

Reserved sales: 1,414.22
1 Like

Hi,
Thank you so much.

Hello,
In book I read a line like below:

In general, @printf allows us to have more control over our output format than we have with print / println .

Is it true?

Sure, just take a look at the examples in the documentation of @printf (via ?@printf in the REPL). Most of these would be a hassle to achieve via print.

On the other hand, print (and show) work for more complicated objects. E.g. you can easily (pretty) print a Matrix M (print(M) or show(stdout, "text/plain", M), but for @printf this would require looping and taking care of the alignment yourself.

1 Like

Hi,
Thank you so much.