How to convert numeric fields into strings with leading zeros?

The solution is:

'000'   ||  tostring("myfield")

(a variable = 'variable') + (string concatenation = ||) + (field = "myfield")

5 -> 0005
50 -> 00050
500 -> 000500

combining variables

'hello'   || ', ' ||  tostring("myfield")

5 -> hello, 5

'hello'   || ', ' ||  tostring("myfield") || ', goodbye'

5 -> hello, 5, goodbye

combining fields

tostring("myfield") || ', ' || tostring("otherfield")

combining other thinks, like geometry

For example, for a point, the x and y coordinates -> (x, y)

'('   ||   $x  ||   ','   ||  $y  || ' )'

and you can format the result

right(  ('000'   ||  tostring(  "myfield" )), 4)

5 -> 0005
50 -> 0050
500 -> 0500

etc.


Another, and possibly more compact, option using 'lpad' (Left Pad) under String Functions which requires three arguments: the field, desired length, and padding character:

lpad("MyField",3,'0')

Tags:

Qgis