Compact string representation of a float

I want the compact (in the sense of IOContext(io, :compact => true)) string representation of a floating point number or vector for inclusion in a Quarto document. Currently I define a function

function compact(x; buf::IOBuffer = IOBuffer())
  print(IOContext(buf, :compact => true), x)
  return String(take!(buf))

Am I missing a more obvious way of doing this?

1 Like

I finally remembered the name Ryu and was able to check functions such as Base.Ryu.writeshortest and could call that directly with true as the value of the compat argument, but that may be even more difficult to explain than my current version.

Why not @sprintf("%.6g", x) (from the Printf stdlib)? This should be pretty similar to :compact=>true (which also limits output to 6 significant digits), but is a lot more explicit, is precisely documented, and gives you a lot more control.

But if you really want to use :compact=>true, you can use the context argument of repr to do it a bit more concisely than what you wrote above: repr(x, context=:compact=>true).