Float64 & format

How can I make Floats appear in scientific or engineering notation? E.g., I want to display, say, 0.0001 as 1e-4.

I know I can do this using the @printf macro, but that just prints the formatted number to the terminal. I need to make it into a string.

How do I format Floats and produce a string?

You can use @sprintf, it’s like @printf but gives the string as return value.

3 Likes

Thanks, that was simple :slight_smile:

1 Like

You can also use the JuliaString/Format.jl package, which has a lot more formatting options (and some more bug fixes).

1 Like

I noticed the upgrade from Formatting.jl to Format.jl, and took a look at it. The documentation seems very rudimentary, but perhaps it is assumed that one checks the documentation of the related Python package?

1 Like

I inherited the documentation from Formatting.jl - and yes, it mostly has the differences documented, where it doesn’t match the Python format function, or C’s printf (for the cfmt function).
If you feel something needs to be better documented, or there is a difference that needs to be mentioned, please make an issue (or better yet, a PR :grin: )

I don’t have background from the C-world (i.e., I’m very shaky on printf/sprintf), and I haven’t used the Python system much for formatting (and very little since 2017…).

What was not clear to me from the Format.jl documentation was… how do I use it? If it is meant to be used in conjunction with printf, I didn’t see that mentioned or exemplified in my quick glancing through the description.

1 Like

You wouldn’t use it with @printf or @sprintf, but more to replace using @sprintf.
If you need to output, instead of building a formatted string, you can simply print it with print, i.e. print(pyfmt("^8d", num))' or print(cfmt(“%10.10”, str)`.

Instead of using Format.jl directly, you could also use JuliaString/StrFormat.jl, i.e. f"This is a C formatted number \%10.3f(num), and this is a Python style format number \{^10.3e}(num)" to create a string, and `pr"This prints the formatted string out, like @printf, for example a string truncated to 8 characters %8.8s(str)"

1 Like