# Compact string representation of a float

**URL:** <https://discourse.julialang.org/t/compact-string-representation-of-a-float/108526>\
**Category:** General Usage\
**Tags:** io, formatting\
**Created:** [January 8, 2024, 4:38pm UTC](https://discourse.julialang.org/t/compact-string-representation-of-a-float/108526 "2024-01-08T16:38:01Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![dmbates](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dmbates/32/44_2.png) [@dmbates](https://discourse.julialang.org/u/dmbates)\
**Post date:** [January 8, 2024, 4:38pm UTC](https://discourse.julialang.org/t/compact-string-representation-of-a-float/108526/1 "2024-01-08T16:38:01Z")

</div>

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](https://quarto.org) document. Currently I define a function

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

```

Am I missing a more obvious way of doing this?

---

<div class="post-metadata">

**Author:** ![dmbates](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dmbates/32/44_2.png) [@dmbates](https://discourse.julialang.org/u/dmbates)\
**Post date:** [January 8, 2024, 5:06pm UTC](https://discourse.julialang.org/t/compact-string-representation-of-a-float/108526/2 "2024-01-08T17:06:52Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [January 8, 2024, 6:35pm UTC](https://discourse.julialang.org/t/compact-string-representation-of-a-float/108526/3 "2024-01-08T18:35:19Z")

</div>

> [@dmbates](#):
>
> Am I missing a more obvious way of doing this?

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`](https://docs.julialang.org/en/v1/base/strings/#Base.repr-Tuple%7BAny%7D) to do it a bit more concisely than what you wrote above: `repr(x, context=:compact=>true)`.
