Grails databinding with decimal delimiter

前端 未结 3 2042
孤城傲影
孤城傲影 2020-12-31 13:30

I have a problem when I use grail automatic databinding \"ex: Test t = new Test(params)\" with decimal delimiter on Double form field. After few search, I\'ve found that it

3条回答
  •  醉梦人生
    2020-12-31 13:36

    I have the same problem here. For example a user in Germany will usually enter a , (comma) as a decimal separator but obviously you cannot prevent him from entering a dot instead ;) Also if you fill the value from Javascript it's quite difficult to get a localized number. So I wrote this small helper method for the controller. It might not cover all possible scenarios, but I need it for entering GPS coordinates. Feel free to suggest improvements.

        /**
         * Replaces , in the param with . an converts it to a Double.
         * @param paramName an array of paramater names
         */
        private convertDicimalParamsToDouble(paramName) {
            paramName.each { it
                def val = params[it]
                if(val) {
                    val = val.replace(",", ".")
                    try {
                        params[it] = Double.parseDouble(val)
                    } catch (NumberFormatException) {
                        //ignore
                    }
                    log.debug("Converted decimal param ${it} with value '${params[it]}' to new value '${val}'")
                }
            }
        }
    

    Then call it like this for example:

    def save() {        
        convertDicimalParamsToDouble(["lat", "lng"])
        ...
    

提交回复
热议问题