2

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.

n92
  • 7,424
  • 27
  • 93
  • 129

2 Answers2

7

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.

Ian Roberts
  • 120,891
  • 16
  • 170
  • 183
  • 1
    Yes, This is always a solution But for using especially g tag in service was my question – n92 Jan 08 '14 at 13:32
2

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
34m0
  • 5,755
  • 1
  • 30
  • 22
  • 1
    From grails 2.1 `import groovy.xml.MarkupBuilder def g = Holders.grailsApplication.mainContext.getBean('org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib')` – Hassan ALAMI Jun 18 '19 at 14:57
  • 1
    in grails 4.0.13 `def g = grailsApplication.mainContext.getBean('org.grails.plugins.web.taglib.ApplicationTagLib');` worked for me – dcdrns Dec 01 '22 at 10:40