Saturday, February 20, 2010

Sunday, February 14, 2010

Can you extract the fractional part of a decimal number using primitives only in Java?

Can you extract the fractional part of a decimal number using Java's primitives only (No String, Math or any other library functions)?

Well the algorithm is a straight forward one:

double decimalNumber = 1234.56;
long wholePart = (long) decimalNumber;
double remainingDecimalNumber = decimalNumber - wholePart;
long fractionPart = 0;
long fractionDigit;
while(remainingDecimalNumber != 0)
    remainingDecimalNumber *= 10;
    fractionDigit = (long) remainingDecimalNumber;
    remainingDecimalNumber -= fractionDigit;
    fractionPart = fractionPart * 10 + fractionDigit;

But, the output will not be what you would expect it to be. The reason is (1.1 – 1) is not equals to (0.1), its (0.10000000000000009) instead. While I understand the importance of precision, is there a simple and easy way to get (0.1) out of (1-1 – 1)? again not using String, Math or other library functions.

UPDATE: It turns out that you can not work on arbitrary-precise floating points using primitives alone. For that you’ll have to either (in recommended order)

1. Use BigDecimal provided by Java, or
2. Use existing methods in other popular third party libraries, or
3. Create your own round/precision method