user3806461
user3806461

Reputation:

Jula REPL number formatting

In MatLab/Octave you could send a command "format long g" and have default numerical output in the REPL formatted like the following:

octave> 95000/0.05

ans = 1900000

Is it possible to get a similar behavior in Julia? Currently with julia

Version 0.3.0-prerelease+3930 (2014-06-28 17:54 UTC)

Commit bdbab62* (6 days old master)

x86_64-redhat-linux

I get the following number format.

julia> 95000/0.05

1.9e6

Upvotes: 6

Views: 2402

Answers (1)

waTeim
waTeim

Reputation: 9235

You can use the @printf macro to format. It behaves like the C printf, but unlike printf for C the type need not agree but is rather converted as necessary. For example

julia> using Printf
julia> @printf("Integer Format: %d",95000/0.05);
Integer Format: 1900000

julia> @printf("As a String: %s",95000/0.05);
As a String: 1.9e6

julia> @printf("As a float with column sized larger than needed:%11.2f",95000/0.05);
As a float with column sized larger than needed: 1900000.00

It is possible to use @printf as the default mechanism in the REPL because the REPL is implemented in Julia in Base.REPL, and in particular the following function:

function display(d::REPLDisplay, ::MIME"text/plain", x)
    io = outstream(d.repl)
    write(io, answer_color(d.repl))
    writemime(io, MIME("text/plain"), x)
    println(io)
end

To modify the way Float64 is displayed, you merely need to redefine writemime for Float64.

julia> 95000/0.05
1.9e6

julia> Base.Multimedia.writemime(stream,::MIME"text/plain",x::Float64)=@printf("%1.2f",x)
writemime (generic function with 13 methods)

julia> 95000/0.05
1900000.00

Upvotes: 6

Related Questions