28 Nov 2009 @ 8:44 AM 

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

Posted By: Zayin
Last Edit: 28 Nov 2009 @ 08:44 AM

EmailPermalink
Tags
Tags:
Categories: java


 

Responses to this post » (2 Total)

 
  1. zayinkrige says:

    New Blog Post -> How to work with currency in Java by using the BigDecimal type – http://www.zayinkrige.com/how-to-work-wi

  2. [...] 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 [...]

Post a Comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.


 Last 50 Posts
 Back
Change Theme...
  • Users » 1
  • Posts/Pages » 38
  • Comments » 61
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight

Links



    No Child Pages.

Portfolio



    No Child Pages.