Converting Float64 to string with run-time generated format string

Hi all,

I’m fairly sure this topic has come up before, either on discourse, or on the old google group, but I can’t seem to find the link. Regardless, I thought I might see if the answer has changed given all the language developments over the past few years.

Given the following code:

x = rand()
@sprintf("%2.2f", x)
fmt_str = "%2.2f"
@sprintf(fmt_str, x)

the first call to @sprintf produces an appropriately formatted string. The second call generates an argument error. My understanding is that this is because the format string input to the @sprintf macro can not be generated at run-time (ie it needs to be known at compile time). Is this correct?

Given v0.7, what options are available to me If I really wanted to convert Float64 to String using a run-time generated format string? What if I do not care about speed (ie the section of code that will do this stuff is not performance-critical)?

I am honestly too embarrassed to post the code that shows how I currently deal with this issue. Let’s just say it involves a lot of if statements and takes an impressive amount of time to compile…

Also, I am willing to entertain the suggestion that I need to re-think my workflow such that I no longer care about converting floating point numbers to strings using run-time generated format strings… but I haven’t worked out a way to do this yet. Currently I like doing this because I have fairly general routines that, deep within, print interesting output for me to read, and sometimes I like being able to control what that output will look like with some options passed in at the beginning of the routine.

Cheers, and thanks in advance to all responders.

Colin

1 Like

Try

Huh! Not sure how I missed that. The section on C-style formatting looks like it was designed to solve exactly the problem I discussed.

Thanks for pointing it out. I’ll try it out tomorrow.

For other readers, I should also add that I just glanced over the source, and the package has no dependencies, and is quite simple itself (so no reason not to use it liberally throughout your codebase, which is nice).

Cheers,

Colin

Another option is:
https://github.com/JuliaString/Format.jl

It is based on Formatting.jl, but includes some interesting features (from a PR by Tom Breloff that he’d made to Formatting.jl that was never merged there), as well as being maintained/updated more frequently.
The one downside is that it needs to be installed via Pkg.clone, because it is not registered.

Awesome, thanks for the additional option, I’ll check it out too.