gabrielsterz
gabrielsterz

Reputation: 25

How to show Numbers in Vaadin Text- or NumberFields formatted in Currency Style?

I just want an editable field show Number as A Currency like

1.444.444,90 

I already checked NumeralFieldFormatter but when i use it with Constructor or Builder. It doesn't matter it always gives me something like 20000.0

NumeralFieldFormatter currencyOne = new NumeralFieldFormatter.Builder()
                .decimalMark(",")
                .decimalScale(2)
                .delimiter(".")
                .thousandsGroupStyle(NumeralFieldFormatter.ThousandsGroupStyle.THOUSAND)
                .build();
currencyOne.extend(textfield);

What do I do wrong or is there a better possibility in vaadin? How can such a big Framework have nothing built in for Currencies or do I simply not find it?

Thanks in Advance

Upvotes: 2

Views: 881

Answers (1)

Simon Martinelli
Simon Martinelli

Reputation: 36203

You can use a Binder with a converter:

public class HelloWorldView extends VerticalLayout {

    private final DecimalFormat decimalFormate = new DecimalFormat("###,###,###.00");

    public HelloWorldView() {
        Binder<Person> binder = new Binder<>(Person.class);

        TextField name = new TextField("Name");
        binder.forField(name)
                .bind("name");

        TextField salary = new TextField("Salary");
        binder.forField(salary)
                .withConverter(new Converter<String, BigDecimal>() {
                    @Override
                    public Result<BigDecimal> convertToModel(String value, ValueContext context) {
                        if (value == null || value.length() == 0) {
                            return Result.ok(new BigDecimal(0));
                        } else {
                            return Result.ok(new BigDecimal(value));
                        }
                    }

                    @Override
                    public String convertToPresentation(BigDecimal value, ValueContext context) {
                        if (value == null) {
                            return "";
                        } else {
                            return decimalFormate.format(value);
                        }
                    }
                })
                .bind("salary");

        binder.setBean(new Person());

        add(name, salary);
    }

Please find the whole example here: https://github.com/simasch/vaadin-formatting

Upvotes: 2

Related Questions