How to use g.formatNumber in grails Service class

2.8k views Asked by At

I want to use g.formatNumber in service, I have tried a below method, Which i got online. This is not working, its giving me the error "Cannot invoke method formatNumber() on null object", The code is below

    import org.springframework.beans.factory.InitializingBean

    class MyService implements InitializingBean {
        boolean transactional = false
        def gspTagLibraryLookup  // being automatically injected by spring
        def g

        public void afterPropertiesSet() {
            g = gspTagLibraryLookup.lookupNamespaceDispatcher("g")
            assert g
        }

      def getFormattedNumber(){
       def number = g.formatNumber(number: 5000,234 , type: "number" , maxFractionDigits: 2)
       return number
     }
}

How to do this.

2

There are 2 answers

1
Ian Roberts On

I want to use g.formatNumber in service

Rather than jumping through the hoops you need to use a taglib within a service, it would be simpler to just use java.text.NumberFormat directly

NumberFormat format = NumberFormat.getNumberInstance()
format.maximumFractionDigits = 2
def number = format.format(5000.234)

If the service method is being called from a web request handling thread then you may wish to use the LocaleContextHolder to get the correct locale for the current web request, rather than just using the server's default.

2
34m0 On

This should work

def g = grailsApplication.mainContext.getBean('org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib');

You will of course need grailsApplication injected by defining it ala

def grailsApplication