Search code examples
javajsfbigdecimal

BigDecimal rounding in jsf 1.1


There is a bug in el-1.0 which jsf 1.1 uses which converts a BigDecimal to double and then back to BigDecimal during the update model phase. This occurs in the ELSupport.java -> coerceToNumber class and was fixed in el-impl-2.1.2-b03. The end result is that if a user enters 54.93, then it results in 54.92999999... when the updateModel phase occurs.

Assume that I do not have the option to upgrade to el-2.1.2-b03 but still must guarantee accuracy of my calculations and what I send to the backend. What is the best rounding strategy to use? I was thinking of simply setting the scale to 2 with a rounding strategy of ROUND_HALF_EVEN whenever the setter method is called in my backing bean during the updateModel phase.

Is there a better solution?


Solution

  • There is no solution for this in JSF 1.1. The two work arounds are to:

    1. Bind to a String and convert to BigDecimal by calling new BigDecimal(string);

    2. Continue binding to BigDecimal but attach a ValueChangeListener where you can manually set the Value in your datamodel prior to calling renderResponse on FacesContext. You must skip the update model phase by calling renderResponse or this will not work.