I use a DataBinder to map values to objects like this:
final var binder = new DataBinder(target);
binder.setIgnoreUnknownFields(false);
binder.bind(new MutablePropertyValues(properties));
Now I have some strings which have a comma as decimal separator and need to be converted into a double.
This gives me the following error because "0,00" can not be converted into a double:
Field error in object 'target' on field 'price': rejected value [0,00];
codes [typeMismatch.target.price,typeMismatch.price,typeMismatch.double,typeMismatch];
arguments [org.springframework.context.support.DefaultMessageSourceResolvable:
codes [target.price,price]; arguments []; default message [price]]; default message
[Failed to convert property value of type 'java.lang.String' to required type 'double'
for property 'price'; nested exception is java.lang.NumberFormatException: For input string: "0,00"]
I don't know how to make DataBinder to accept the comma as decimal separator or use the locale Locale.FR
(which is the data source locale).
This didn't help:
LocaleContextHolder.setLocale(Locale.FRANCE);
Locale.setDefault(Locale.FRANCE);
Can someone tell me how to handle the decimal comma?
This is my test case:
class DataBinderTest {
class Foo {
public double price;
public void setPrice(double price) {
this.price=price;
}
}
@Test
void testMapping() throws BindException {
final var properties = new Properties();
properties.setProperty("price","0,00");
final var binder = new DataBinder(new Foo());
binder.setIgnoreUnknownFields(false);
binder.bind(new MutablePropertyValues(properties));
if (binder.getBindingResult().hasErrors()) {
throw new BindException(binder.getBindingResult());
}
}
}