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...
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...
Nevermind... string(round(Float64(pi); digits = 8))
Jesper Stemann Andersen has marked this topic as resolved.
There is also Printf.@sprintf
from the standard library:
julia> using Printf
julia> Printf.@sprintf("%.8f", pi)
"3.14159265"
Jesper Stemann Andersen has marked this topic as unresolved.
Ah - nice.
It is also still a bit puzzling to me how round
ends up affecting string
...
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
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.
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
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 NaN
s)
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.
Jesper Stemann Andersen has marked this topic as resolved.
Last updated: Nov 06 2024 at 04:40 UTC