Convert String Ex. 1,520,30 to a BigDecimal using the Spring MVC @InitBinder

5

I have a screen where I work with jQuery Mask monetary value masks, when the user performs the submit form value returned to my controller is Ex :. 1.340,34.

The Bean attribute that bind bind is a BigDecimal . Soon I had to create a CustomNumberEditor and register it in an @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 do not look right, that is, the example number above is 1340 in the database, the right one being 1,340.34. >

How can I perform such a conversion correctly?

    
asked by anonymous 29.07.2015 / 15:57

1 answer

3

With BigDecimal it is interesting to have a method for setting the rounding scale and the precision of the value.

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

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

Another way is to have your own method to manipulate the value with the scale and precision you want.

link

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

    
09.12.2015 / 21:49