Extending a string by adding 0's to the end

Suppose I have a process that receives strings like the following:

“1.542”
“1.293”
“1.652”
“1.297”

Every now and again, however, the process receives a string with fewer “decimal places”. For example:

“1.9”

I wish to create a function that takes a given string received, checks if it has less than three “decimal places”, and if so, extends the string by adding 0’s to the end to return an updated string with three decimals. For example, inputting “1.9” to the function would return “1.900”

What Julia syntax is useful for this task?

1 Like

I had a similar problem in: Generate equal length strings from numbers by padding with "0"? - #2 by fredrikekre, except I needed padding on the left. There is also an rpad function available. I hope it helps.

3 Likes

You may use @sprintf for this. It’s defined in Printf.

julia> @sprintf "%.3f" parse(Float64,"1.9")
"1.900"

Admittedly this is a somewhat roundabout way of going at it, and ideally you’d want a solution that does not convert to floating point.

1 Like

For padding integers with zeros on the left, you could also use string, although that was not mentioned in the cited thread.

2 Likes
julia> using BenchmarkTools

julia> function rpad(s,c,l) while length(s)<l; s*=c; end; return s; end
rpad (generic function with 2 methods)

julia> function rpad2(s,c,l) add=l-length(s); if add<=0 return s; end; s*=repeat(c,add); return s; end
rpad2 (generic function with 1 method)

julia> s="1.1"
"1.1"

julia> @btime rpad($s,'0',10)
  387.685 ns (14 allocations: 448 bytes)
"1.10000000"

julia> @btime rpad2($s,'0',10)
  48.435 ns (2 allocations: 64 bytes)
"1.10000000"

Sorry, I am missing the context for these benchmarks: we already have rpad, are you suggesting that it could be improved?

1 Like

Oooops, no, i wasn’t sugesting that. I just read the OP, started to implement two versions, and checked their peformance and thought, OP would be interested as he wrotes

I wasn’t very concentrated, sorry for making you (and probably others) puzzled. :flushed:

1 Like

Note two details:

  1. rpad in base does virtually the same as oheil’s rpad2 - except that it can take more than 1 character as “padding” string.
  2. The OP didn’ specify if the left side of the numbers will always have one digit. If not, the n argument to rpad should be the sum of the number of decimals and the position of the decimal point (e.g. findfirst('.', s)).