9

This question builds on a previous question I came across at gis.stackexchange: How to easily edit attribute data using Regular Expressions?

Perhaps someone can point me in the right direction?

I have a vector shapefile of contour lines. In the attribute table I have already converted a field called FEET consisting of integer data containing elevation values to a string field called Label. Additionally I successfully appended a ' to the end of the string so that when the data is labeled it will be read as feet.

The next thing I am attempting to do is to insert a comma between the first two values of the string only if the string length is greater than 4, or so that a comma will only appear between the thousands and hundreds digits in the Label field. The length has to be greater than 4 because I'm also counting the '

My code so far is:

case when  length( "Label") >4  then regexp_replace( "Label", '^([0-9])+([0-9]{3}\')$','$1 , $2') else "Label" end

however the regexp_replace function doesn't seem to accept the group variables $1 $2 in the 3rd parameter of the function.

I've looked at http://docs.python.org/2/library/re.html as the field-calculator regex is from what I understand based on python's use of regex but haven't been able to figure this out. Maybe what I'm attempting to do isn't possible yet with this function in field calculator in QGIS 1.8 on mac OSX. Or more likely my syntax is wrong as I'm a novice programmer and somewhat new to regular expressions.

4
  • Does it have to be coded - wouldn't a simple way be to (in Excel, or similar) create a new column which had the label in it formated how you wanted it - all you would have to use is a few concatenate command. Apr 21, 2013 at 6:06
  • Yes that would be one way of solving the problem, however I'm trying to solve it from within QGIS or with python.
    – clhenrick
    Apr 21, 2013 at 17:00
  • @chrishenrick - did my answer solve it for you?
    – Stev_k
    Nov 26, 2013 at 19:15
  • @Stev_k haven't had time to try it yet, will do so soon and let you know. Thanks for your help!
    – clhenrick
    Nov 26, 2013 at 22:33

6 Answers 6

9

QGIS has created a function called format_number to address this. You simply do format_number(12345,0) to get 12,345.

3
  • That's good news. Though part of my question involves appending a ' to the end of the number to represent "feet". Would you be able to do the following in QGIS with this function? format_number(12345,0) + "'"
    – clhenrick
    Jul 30, 2015 at 15:04
  • I believe the answer would be concat(tostring(format_number(12345,0)), "'"). You would have to first turn the formatted number into a string using the tostring function and then use the concat function to attach the ' at the end.
    – Minh
    Jul 30, 2015 at 15:21
  • Makes sense, this is what I posted in my answer above and worked: concat( format_number( "Field_name" , 0) , '\'')
    – clhenrick
    Jul 30, 2015 at 18:46
8

Using two string functions in the QGIS calculator on version 2.6 Mac OS X I was able to accomplish this. Here are the steps:

  1. Using the field calculator create a new field that is a string type with a relevant width.

  2. Run the following expression to set the value of the field:
    concat( format_number( "Field_name" , 0) , '\'')

This created a column with a string formatted as I wanted so for example the number 2000 would be formatted to 2,000' with the trailing ' which stands for feet.

3

You can do digit grouping easily in Python. Here's a function that I've used, which I think I found on StackOverflow:

def digitgroup(n, sep = ','):
    if n == "": n = 0
    s = str(n)[::-1]
    groups = []
    i = 0
    while i < len(s):
        groups.append(s[i:i+3])
        i += 3
    return sep.join(groups)[::-1]
1
  • thanks for the suggestion, dmahr. however I'm unclear on how to implement this function in QGIS. I attempted cutting and pasting this function into the field calculator expression and setting n to my field name but with no luck. Is there a way to implement python scripting in QGIS outside of field calculator?
    – clhenrick
    Mar 26, 2013 at 22:05
3

In QGIS, the function "format_number" under the string menu in field calculator reformats numbers to locale specific separators and decimal places.

1
  • see my comment in Minh Mai's answer.
    – clhenrick
    Jul 30, 2015 at 15:06
3

For people whose locale does not fit the desired formatting display, format_number is not an adequate solution. For example, on my French system, format_number(2000) always displays 2 000 (with a space as thousands separator) independently of QGIS language settings, although I sometimes need an "English-style" display -- eg. 2,000.

In such cases, the following (and somewhat cumbersome) approach works (at least on QGIS 2.18):

if (your_field > 1000,
  concat(
    floor(your_field/1000),
    ',',
    your_field-1000*floor(your_field/1000)
  ),
  your_field
)

You can of course replace ',' with whatever thousands separator you want. Note that this expression only works with numbers lower than 1,000,000.

1

It's a bit more complicated than that in QGis. As per this article, you have to create your own function definition in Python, then import it into QGis (this can be done automatically on startup). This may seem tricky, but you only need to do it once and it will always be there!

This is the function I used, based on dmahr's above. Not sure how it deals with strings, as I modified the code a bit.

from qgis.utils import qgsfunction
from qgis.core import QGis

@qgsfunction(2, "Python") # number of arguments
def thousands_separator(values, feature, parent): # values are the arguments passed in
    # this is the documentation for your function which you will see in QGis
    """
    Adds a separator to values over 1000\n        
    Parameters: (n, sep) \n                   
    n = expression_field \n
    sep = desired separator (default is ",")
    """ 
    number = values[0]                        # the first argument (which in the
    separator = values[1]                     # labelling case is a field name
    if separator == '':
        separator = ','
    s = str(number)[::-1]
    groups = []
    i = 0
    while i < len(s):
        groups.append(s[i:i+3])
        i += 3
    return separator.join(groups)[::-1]

You then save that in .qgis/python, import the file into QGis using the console, then it will show up in "Python" functions in the label tool.

The expression I used is: thousands_comma( "[field_name]" ,',')

3
  • Also, I didn't see what version you were using - you should upgrade to 2.0 to make this work
    – Stev_k
    Nov 20, 2013 at 13:09
  • hi, thank you and sorry for the late response. I'm on v2.6 Mac OS X 10.9.5 Where exactly do I place the python file? I assume somewhere in /Applications/QGIS.app/Contents/Resources/python/ ?
    – clhenrick
    Dec 10, 2014 at 1:49
  • See my answer below for a much simpler fix. I dont' know what version is needed to make it work, though. Dec 11, 2014 at 22:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.