How to format an int as a zero padded string?
-
Let's say that I have an int variable x >= 0 which I want to format as a zero padded 7 digits string, similar to "%07d" in some programming languages. For example 127 -> "0000127". Is there a simple way to achieve? Currently I am using the brute force code below.
if global.x < 10 set global.y = "000000" ^ global.x elif global.x < 100 set global.y = "00000" ^ global.x elif global.x < 1000 set global.y = "0000" ^ global.x elif global.x < 10000 set global.y = "000" ^ global.x elif global.x < 100000 set global.y = "00" ^ global.x elif global.x < 1000000 set global.y = "0" ^ global.x else set global.y = "" ^ global.x echo "" ^ global.y
-
Ok, this is simpler but I wonder if there is a single statement format solution.
var decade = 10 var result = "" ^ global.X while iterations < 6 if global.X < var.decade set var.result = "0" ^ var.result set var.decade = var.decade * 10
Alternatively, the iteration can be on the length of the string if these is a length function (?).
-
Ok, here is a simpler one. Took me some time to realize that the # unary operator require () to work.
var pad = "" ^ global.x while #(var.pad) < 7 set var.pad = "0" ^ var.pad
-
-
@fcwilt, I am generating a unique id that is used to form a file name. Ideally would do it with a timestamp such as 231219-071453 but couldn't find a reliable way to generate it using gcode.
-
@zapta said in How to format an int as a zero padded string?:
Took me some time to realize that the # unary operator require () to work.
It works without the () for me, using RRF 3.5.0-rc.2.
-
@dc42, must be fixed along the way. On 3.4.6 this is what i get
var x = "123" echo "String: " ^ var.x echo "Length: " ^ #var.x