Convert String Ex. 1.520.30 to Bigdecimal using Spring MVC @Initbinder

Asked

Viewed 711 times

5

I have a canvas on which I work with the monetary value masks of jQuery Mask, when the user performs the Submit of form the value returned to my controller is Ex:. 1.340,34.

The attribute in my Bean that the bind is a Bigdecimal. Soon I had to create a Customnumbereditor and register it in a @Initbinder as shown below:

@InitBinder
public void initBigDecimalBinder(WebDataBinder binder) throws Exception {
    DecimalFormat df = new DecimalFormat();
    DecimalFormatSymbols dfs = new DecimalFormatSymbols();
    dfs.setGroupingSeparator('.');
    dfs.setDecimalSeparator(',');
    df.setDecimalFormatSymbols(dfs);
    binder.registerCustomEditor(BigDecimal.class, new CustomNumberEditor(BigDecimal.class, df, true));
  }

The Biggest problem is that the values are not correct, ie the example number right above is 1340 in the database, and the right one would be 1.340.34.

How can I perform such a conversion correctly?

  • 1

    João, your doubt helped me a lot, adjusting the accuracy via note solved my problem

1 answer

3

With Bigdecimal it is interesting to have a method to set the rounding scale and the accuracy of the value.

If you are using JPA for persistence, an easy way to do this is with the @Column annotation.

@Column(precision = 2, scale = 3)
private BigDecimal valor;

Another way is to have a method of handling the value with the scale and precision you want.

https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html#setScale-int-int-

Make sure the table in the database has the correct format to suit decimal numbers.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.