In Grails we can convert a request parameter to a type directly. We must then use the int(), short(), byte(), long(), double(), float(), boolean() or list() methods that are added to the params object available in our controllers.

Since Grails 2.3 we can also pass a default value, which is used when the request parameter is not set. In the following controller we use the double() method and define a default value of 42.0.

// File: grails-app/controllers/com/mrhaki/grails/SampleController.groovy
package com.mrhaki.grails

class SampleController {

    def index() {
        // Get request parameter named v.
        // Use default value 42.0 if not set.
        final double value = params.double('v', 42.0)
        [value: value]
    }

}

The following test shows that the default value is returned if the request parameter is not set, otherwise the value of the request parameter is returned:

// File: test/unit/com/mrhaki/grails/SampleControllerSpec.groovy
package com.mrhaki.grails

import grails.test.mixin.TestFor
import spock.lang.Specification

@TestFor(SampleController)
class SampleControllerSpec extends Specification {

    def "request parameter v must return default value if not set"() {
        expect:
        controller.index().value == 42.0
    }

    def "request parameter v must return value set"() {
        given:
        params.v = '10.1'

        expect:
        controller.index().value == 10.1
    }

}

We can use the same methods now also to get attribute values in a tag library. So we can do a type conversion and provide a default value if we want to. In the following tag library we use this in the tag sample:

// File: grails-app/taglib/com/mrhaki/grails/SampleTagLib.groovy
package com.mrhaki.grails

class SampleTagLib {

    static namespace = 'sample'

    static returnObjectForTags = ['sample']

    def sample = { attributes, body ->
        final double value = attributes.double('v', 42.0)
        value
    }

}

With the following Spock specification we can see that the default value 42.0 is used if the attribute v is not set. Otherwise the value of the attribute is returned:

// File: test/unit/com/mrhaki/grails/SampleTagLibSpec.groovy
package com.mrhaki.grails

import grails.test.mixin.TestFor
import spock.lang.Specification

@TestFor(SampleTagLib)
class SampleTagLibSpec extends Specification {

    def "attribute v returns default value if attribute is not set"() {
        expect:
        applyTemplate('') == '42.0'
    }

    def "attribute v returns value if attribute v if set"() {
        expect:
        applyTemplate('', [v: 10.1]) == '10.1'
    }

} 

Code written with Grails 2.3.

Original article

shadow-left