I'm just wondering if it's possible to tell an @InitBinder that empty float values in a form would be converted to 0.
I know that float is a primitive data type but I'd still like to convert null or empty values to 0.
If that is possible, how can i achieve that?
Otherwise I'll just make a workaround using a String instead of a float
Yes you could always do that .Spring have a
CustomNumberEditor
which is a customizable property editor for any Number subclass like Integer, Long, Float, Double.It is registered by default by BeanWrapperImpl,but, can be overridden by registering custom instance of it as custom editor.It means you could extend a class like thisAnd then register it normally in you controller:
This should do the task.
Define a subclsss of CustomNumberEditor as
Then in your controller class (I create a BaseController for all my application controllers, I need this behavior for all the numeric primitive types in my application, so I simply define this in my BaseController), register binders for the various primitive types. Note that the constructor parameter of MyCustomNumberEditor must be a subclass of Number, instead of primitive class type.