Injecting method to convert String number to number (Having , $ brackets)

21 / May / 2010 by Uday Pratap Singh 0 comments

Recently in my project we have use case where users have the habit of entering number as 100,000 and they write the -ve numbers as (100,000). Some times they also pur $ with the number field
Initially when we were not aware of this we were populating the object like

Expense expense =new Expense(params)

This throw exception as the user type “,” in the number then we moved to


This handles the number with “,” very gracefully.
Now the real use case came into picture where we need to ignore $ and change the number enclosed with brackets to -ve number. We dont want to change our code for this so we came up with the solution of injecting a method in String class which will do all the things for us and we added a method in the project bootstrap which is something like .

String.metaClass.convertToNumber = {
            String stringNumber = delegate?.toString()
            stringNumber = stringNumber.replaceAll("[,]|[(]|[)]|[\$]",'')
            Float number = 0
            if (stringNumber.isNumber()) {
                number = Float.parseFloat(stringNumber)
                if (delegate?.toString()?.endsWith(")")) {
                    number = -number
            return number

And we added the line in the Application Filter

params?.totalCost = params?.totalCost?.convertToNumber()

It just do the trick for us and we dont need to change our code. I think its one of the correct way to handle such requirement

Hope it helps
Uday Pratap Singh


Leave a comment -