I am using Vaadin 8 and binding my business object attributes to fields in a form. It appears that when a float value greater than 999 is retrieved from a business object and displayed in a text field, commas are added as place separators. For example, it seems that 1023.4 would be displayed as “1,023.4”. Is that the expected behavior? If so, can i prevent it? Thanks. -Dan
Can you share a code example where this behavior is reproducible?
Hi Olli, Thanks for getting back to me. This code shows the behavior I am asking about. -Dan
package showfloats;
import javax.servlet.annotation.WebServlet;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.data.Binder;
import com.vaadin.data.converter.StringToFloatConverter;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.TextField;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
@Theme("mytheme")
public class MyUI extends UI {
@Override
protected void init(VaadinRequest vaadinRequest) {
final VerticalLayout layout = new VerticalLayout();
Person person = new Person(1234.56f);
setContent(layout);
Binder<Person> binder = new Binder<>();
TextField floatField = new TextField("the float");
layout.addComponents(floatField);
binder.forField(floatField).withConverter(new StringToFloatConverter("Must be a float"))
.bind(Person::getTheFloat, Person::setTheFloat);
binder.setBean(person);
}
@WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true)
@VaadinServletConfiguration(ui = MyUI.class, productionMode = false)
public static class MyUIServlet extends VaadinServlet {
}
static class Person {
float theFloat;
public Person(float f) {
this.theFloat = f;
}
static Float getTheFloat(Person person) {
return person.theFloat;
}
static void setTheFloat(Person person, Float f) {
}
};
}
What’s happening there is that the StringToFloatConverter
uses the current Locale
to set up the NumberFormat
that’s used to make the float to String conversion. You can create a custom Converter
to configure the used format in the getFormat
method yourself:
public static class MyStringToFloatConverter extends StringToFloatConverter {
public MyStringToFloatConverter(String errorMessage) {
super(errorMessage);
}
@Override
protected NumberFormat getFormat(Locale locale) {
NumberFormat instance = NumberFormat.getInstance(locale);
instance.setGroupingUsed(false);
return instance;
}
}
Thanks, Olli. That seems to do just what I wanted. -Dan