Are your Java devs killing your business with data type issues?
So you thought you would outsource your Java development overseas and save a buck or two? Now you find out you cannot account for thousands of dollars in your general ledger and your customers are complaining that they are getting ripped off (or they are thanking you for unexpected discounts). If this sounds familiar, read this post carefully.
If you are doing Java development and interacting with currency values, then you must be sure you are representing those values with the correct data type. By that, I mean using the correct Java object.
As a background, Java supports the following primitive data types:
- int
- char
- byte
- short
- long
- float
- double
- boolean
- void
Integer based data types (int, short, long) do not support the 2 digit decimals that represent the fractional dollars (or euros, pesos, etc). char, boolean, void, and byte also are not appropriate as you cannot do proper math functions on them. They also are not large enough to represent certain large values (i.e. the U.S. national debt .. oh now that THAT is saying something!). That leaves float, and long, which do support decimal points. If your developers have come to that conclusion and have thus coded your general ledger using these primitives, you may now start looking for new developers as this is WRONG!
Why? Simple. Just answer the following question. What does the following produce?
public class HopeAndChange
{
public static void main()
{ long five = (long) 5.00;
long cost = (long) 1.90;
System.out.println(five-cost);
}
}
If you say 0.10, you would be tragically wrong. It would print “4”. Why? Both float and double use binary floating point arithmetic. Many decimals cannot be represented in binary. So. What’s the solution? That is to use a compound object representing real currency. BigDecimal is a good candidate for that is it can represent very large numbers, and supports decimal values very well. Many software tools will miss this point – its not an easy one to catch. It does not generate an error. One way is to ensure that any code that does calculations has associated unit tests (i.e. JUnit). Rational Application Developer in particular has built in features that support code coverage. You can also update its Software Analyzer built in tooling to help identify standard nomenclature variables being represented by a floating point.
This test above is also a good question for an interview for possible employment candidates. If they cannot accurate tell you what this produces, or especially, why it does not produce the expected results… tell them you’ll ‘let them know’.