Hi everyone,
I want to convert a number to a string, but keeping the trailing zeros:
string(1) > “1”
string(1.0) > “1.0”
string(1.00) > “1.0” - How do I get the result “1.00”?
Thanks to all.
Hi everyone,
I want to convert a number to a string, but keeping the trailing zeros:
string(1) > “1”
string(1.0) > “1.0”
string(1.00) > “1.0” - How do I get the result “1.00”?
Thanks to all.
Use Printf and then sprintf.
Thanks, but the issue is that we don’t know a priori the number of decimals,
It should work as follows
string_to_number(n) =
string(n)
And this should result in a string with exact same number of decimals of n
The problem is that the computer’s floating-point representation of numbers doesn’t include any information about how many zeros the user typed, so we can’t reconstruct that information for the output. It might help to know the broader context of what you’re trying to do - can you expand on your use-case?
…
I think there is some confusion on concepts here.
In Julia, and most other languages, 1.0 == 1.00
, the two are the exact same value and it is impossible to distinguish between them inside a program. Julia (and many other languages) do not save anywhere the number of decimal places that were explicitly denoted in the literal was first used for it.
Thanks for the replies.
The use case is, given a range, trying to find a step based on typed decimal cases, e.g.:
[0,1] > step=1
[0.0, 1.0] > step=0.1
[0.00, 1.00] > step = 0.01
…
Your problem would make sense if the input is read from the terminal as strings. Is it the case?
Well, the input is read from CSV files.
Currently numbers are read as numbers, but I guess it won’t be hard to read them as strings.
If that is typed as a string it is possible to write a cumbersome function to extract the number of decimals, such as:
julia> range = "[0.00, 1.00]"
"[0.00, 1.00]"
julia> length(split(split(replace(range, r"[^0-9.]" => ' '))[2],".")[2])
2
(there are probably more smart ways to do that with regular expressions)
Or something simple like
function count_after_dot(str)
# assumes `str` is a valid number
seen_dot = false
trailing = 0
for c in str
if c ≡ '.'
seen_dot = true
else
trailing += seen_dot
end
end
trailing
end
julia> count_after_dot("1.00")
2
Another simple solution:
str = ["1", "1.", "1.0", "1.00", "1.000"]
[occursin(".", s) ? length(split(s,".")[2]) : 0 for s in str]
0
0
1
2
3
And another solution (non allocating)
str = ["1", "1.", "1.0", "1.00", "1.000"]
[findfirst('.', x) |> z -> z === nothing ? 0 : length(x) - z for x in str]
This really doesn’t seem like the right way to specify stepsize, it seems highly unorthodox. Why not clearly specify stepsize explicitly?
Thanks for the replies.
Yes, specify the stepsize is an option, this ‘unorthodox’ one is only for having a default size if the user does not specify any.