Separating double into integer and decimal parts

You could do a String split(...). And then Integer parseInt(...) to get back the two integer components.


Depending on the number of decimal digits, you could use this method:

double number = 24.4;

int integer = (int)number;
double decimal = (10 * number - 10 * integer)/10;

System.out.println(decimal); 

Explanation: Remove the decimal points, do the subtraction, and finally return the decimal point back to its original location!


This is because doubles aren't exactly "real numbers" - remember there are infinite number of real numbers in any range, while there are only finite number of digits in double - thus finite number of values, so some round off must occure.

The fact is, 24.4 cannot be exactly represented by double - so the fraction of your number really is something around 0.3999....
If you want an exact solution - you should use a library that gives you exact values for decimals, such as BigDecimal.

If you want to understand more about this issue of doubles being not exact - you should read more about floating points arithmetics, and this article, though high level, is also a must in order to really understand what's going on.

If you cannot understand these article just yet - just take into consideration: If you need an exact value - doubles cannot provide it - and you should use a library if this is the case.

Tags:

Java

Math