Saturday 19 October 2019

qgis - How to format labels with leading zeroes?


I'm trying to display a number next to a symbol in QGIS 2.0.1 - The numbers are from an integer-field in a postgresql database.


The goal is that single digit numbers get a leading 0. Examples:



  • 12 --> 12

  • 10 --> 10

  • 9 --> 09

  • 0 --> 00



In the menu


 layer properties --> labelling --> formating

I switch on "number formatting" and then enter a custom expression. I tried these two codes with various combinations of ", ' and more brackets, but none of them work:




  • 1


    CASE

    WHEN "Value" <10 THEN rpad("Value", 2, 0)


    END


  • 2


    CASE

    WHEN "Value" <10 THEN "0" || "Value"

    END



EDIT:


For any other person having trouble with this: Turn of "number formatting". It seems to be the reason why leading zeros are removed from the rpad function.


Enter the following in the regular "layer labeling" box:


  rpad("Field", 2, 0)

and everything will work fine. But if you also activate number formatting it will take away the leading zeros.



Answer



We have the rpad function for that:



rpad('1', 2, '0') 
rpad('10', 2, '0')

result


01
10

rpad("yourcolumn", 2, '0')



rpad() function


Returns a string with supplied width padded using the fill character.


Syntax rpad(string, width, fill)


Arguments


string - is string. The string.
width - is int. The length of the new string.
fill - is char. The character to padd the remaining space with.


Example


rpad('Hello', 10, 'x') → 'xxxxxHello'




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...