Hi, I’m designing an input form for bookkeeping.
So it’s important to align all numbers the same and always show monetary amounts with two decimal places after the comma.
How can I reach this using BigDecimalField in Vaadin 14.1.17?
I tried calling BigDecimal.setScale in a Converter class and also in the setter- and getter-methods in the bound datamodel-class.
Behaviour stays the same: when the user changes e.g. “123,00” to “123”, then the BigDecimalField just shows “123”, but unfortunately not “123,00”.
The workaround I ended up with was a value change listener on the field that check the scale() of the new value and does setValue again if the scale is not as expected. This approach does, however, have a couple of unwanted side effects as well
As a workaround for now you should be able to get this behaviour by adding an event listener which would update the value with the correct format every time the user changes it. Should be doable at least on the client side by adding a listener to the change event of the field with some JS code for modifying the value. Might also be possible using a server side ValueChangeListener and having it do something like setValue(value.setScale(2)) (though I’m not sure if this server side approach works).
EDIT: Oops I guess I had this tab open a bit too long since I didn’t see those previous answers before posting mine.
Tarek Oraby:
Another possible solution is to use JavaScript to target the input field of the vaadin-big-decimal-field component, like so:
Your solution won’t work for any vaadin-big-decimal-field elements that might be inside shadow roots (e.g if you’re defining your layout with PolymerTemplate). Also your code with parseFloat won’t parse the number correctly in all cases depending on the Locale like in the example in original post with comma as a decimal separator (it would just drop the decimals).
Thinking about it, it does not exactly nail the OP’s question, but the question people often search the web for and then find this thread. The question that goes with my answer would really be “I need BigDecimalField to allow only certain numeric inputs, such that there’s only a fixed number of digits right of the decimal separator (also known as descendants)”.