Tuesday, February 18, 2014

Rounding Financial Numbers in Java with HALF_EVEN: what you should know

Dealing with financial application is always appealing and also sensitive. I will rather leave the appealing part to you and go to the sensitive part. I had a bad luck to develop an application for accounting. Every things seemed ok till the D-day came.  Hey Soulemane what have you done ?  Then what really happen ?
Trust me these accounts people worship numbers, they don't even tolerate a slight deviation of 0.0000001 cent. 

 Now coming back to HALF EVEN what does javadoc really say about it ?

Rounding mode to round towards the "nearest neighbor"  unless both neighbors are equidistant, in which case, round  towards the even neighbor. Behaves as for   RoundingMode.HALF_UP if the digit to the left of the   discarded fraction is odd; behaves as for  RoundingMode.HALF_DOWN if it's even. Note that this   is the rounding mode that statistically minimizes cumulative   error when applied repeatedly over a sequence of calculations.   It is sometimes known as "Banker's rounding," and is   chiefly used in the USA. This rounding mode is analogous to   the rounding policy used for float and double   arithmetic in Java. 
Example:

Input NumberInput rounded to one digit
with HALF_EVEN rounding *
5.5 6
2.5 2
1.6 2
1.1 1
1.0 1
-1.0 -1
-1.1 -1
-1.6 -2
-2.5 -2
-5.5 -6

In addition to that I would rather add the following explanation when you are in the middle i.e 5  :



Before the account take his/her calculator and start arguing with you get prepare as he might what 12. 455  to be 12. 46 instead of 12. 45. 

However this remain an opened issue feel free to share your experience by dropping a comment.

No comments:

Post a Comment