Stream: helpdesk (published)

Topic: ✔ Customizing conversion of Real to String


view this post on Zulip Jesper Stemann Andersen (Sep 07 2023 at 23:00):

A basic question: How to get from e.g. the Float64 Float64(pi) to a String with a specified number of decimal digits?

string has keyword arguments for specifying base and padding, but somehow seems to miss a digits (and sigdigits) keyword argument like round has...

view this post on Zulip Jesper Stemann Andersen (Sep 07 2023 at 23:07):

I guess something like value = Float64(pi); N = 8; join(reverse(digits(round(Int, value * (10^N)))), "") can be adapted to do what I would like...

view this post on Zulip Jesper Stemann Andersen (Sep 07 2023 at 23:10):

Nevermind... string(round(Float64(pi); digits = 8))

view this post on Zulip Notification Bot (Sep 07 2023 at 23:10):

Jesper Stemann Andersen has marked this topic as resolved.

view this post on Zulip ederag (Sep 08 2023 at 08:49):

There is also Printf.@sprintf from the standard library:

julia> using Printf

julia> Printf.@sprintf("%.8f", pi)
"3.14159265"

view this post on Zulip Notification Bot (Sep 08 2023 at 08:50):

Jesper Stemann Andersen has marked this topic as unresolved.

view this post on Zulip Jesper Stemann Andersen (Sep 08 2023 at 08:51):

Ah - nice.

It is also still a bit puzzling to me how round ends up affecting string...

view this post on Zulip Jesper Stemann Andersen (Sep 08 2023 at 08:53):

I found string in https://github.com/JuliaLang/julia/blob/master/base/ryu/Ryu.jl#L122 , but neededdigits seems to be 309+17 for Float64: https://github.com/JuliaLang/julia/blob/master/base/ryu/Ryu.jl#L16

view this post on Zulip ederag (Sep 08 2023 at 09:26):

needdigits is the maximum size required to faithfully represent any floating point number of a given type.
then writeshortest is probably trimming it down with some heuristics.

view this post on Zulip Sukera (Sep 08 2023 at 09:46):

round itself doesn't affect string at all - it's just that the rounding of pi has the effect of only requiring exactly that many digits to be printed

view this post on Zulip Sukera (Sep 08 2023 at 09:47):

string (and printing) of floating point values in julia writes the shortest possible representation such that parsing the value back gives the exact same number (except for NaNs)

view this post on Zulip Sukera (Sep 08 2023 at 09:48):

for exact printing purposes, I'd always prefer @printf with a specified precision over the string(round(..)) roundabout, because it makes the intent of "I only want to print this many digits" clear.

view this post on Zulip Notification Bot (Sep 08 2023 at 13:30):

Jesper Stemann Andersen has marked this topic as resolved.


Last updated: Nov 06 2024 at 04:40 UTC