Tuesday, 7 January 2020

qgis - How to convert numeric fields into strings with leading zeros?


I'm trying to define an action in Quantum GIS using on of my fields but I have some problems with its format.


I have a numeric string like '5' and I need to have a format like '005'. I've tried function "tostring(myfield)" but I am not able to define the format that I want.



Is there any way to do something like tostring(myfield,"000")?


What I'm looking for is a function like this one: http://office.microsoft.com/en-us/excel-help/text-HP005209313.aspx?CTT=5&origin=HP005204211



Answer



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.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...