As most of you are aware, when working with currency values, FLOAT types just don’t cut it due to their innaccuracy in handling of decimal places. For example – 0.0006 is stored as 0.0005998035. For most instances this is acceptable, BUT when you start working with large values, it becomes a problematic.
Lets say we are writing a banking transaction module that handles 10 million transactions a day. This would result in an inbalance of (10 000 000 x 0.0006) – (10 000 000 x 0.0005998035) = (6000) – (5998.035) = 1.965 out of balance every day. I’m sure you can see why this would become a problem.
The solution? java.math.BigDecimal
However, be warned! BigDecimal isnt a primitive datatype, so you cannot handle it like you would a float.
Lets look at a basic example
//declare and initialize variables BigDecimal customer_tx_amount; BigDecimal customer_tx_vatamount; BigDecimal vatrate = new BigDecimal("14"); //calculate vatrate divider. //if vatrate = 14%, then to work out the exclusive amount, we divide the inclusive amount by //((100+14)/100), or 1.14 vatrate = vatrate.add(new BigDecimal("100")); //we want 6 decimal places vatrate = vatrate.divide(new BigDecimal("100"), 6, BigDecimal.ROUND_HALF_UP); customer_tx_amount = new BigDecimal("235345.37"); customer_tx_vatamount = customer_tx_amount.divide(vatrate, 6, BigDecimal.ROUND_HALF_UP); customer_tx_vatamount = customer_tx_amount.subtract(customer_tx_vatamount); |
So, as you can see, bigdecimal is accurate, but rather clunky to use.
In most instances you will be happy using float, but if you require extreme accuracy, then BigDecimal is definitely the way to go

Categories
Tag Cloud
Blog RSS
Comments RSS
Last 50 Posts
Back
Void « Default
Life
Earth
Wind
Water
Fire
Light 
New Blog Post -> How to work with currency in Java by using the BigDecimal type – http://www.zayinkrige.com/how-to-work-wi…
[...] This post was mentioned on Twitter by Zayin Krige, Zayin Krige. Zayin Krige said: New Blog Post -> How to work with currency in Java by using the BigDecimal type – http://toast.tw/1009qh [...]