I am trying to separate a double into the integer and decimal parts
So for example, the number 24.4 should be separated into 24 and 4.
int integer =
Here is a small method I wrote to accomplish this:
/**
*
* @param n
* @return
*/
private static double getFractionalPart(double n) {
if (n > 0) {
return n - Math.floor(n);
} else {
return ((n - Math.ceil(n)) * -1);
}
}
![Here is my Solution][1]
here is my solution. I used a simple method in C Programming to split the Fractional Numbers in two Different Integers...Here below is the Code
#include<stdio.h>
void main()
{
float x=24.56; int y=(int)x; float z=(x-y)*1000000000; int zd=(int)z;
printf("%lf",x);
printf("\ninteger Part %d\n",y);
printf("\nDecimal Part %d\n",zd);
}
Output
24.559999 integer Part 24
Decimal Part 559999488
I figured out the way with little workaround and I am sure it works for all the cases.
The code says it all.
double number = input.nextDouble(); // 234.025
String s = Double.toString(number); // "234.025"
s = "0" + s.substring(s.indexOf(".")); //"0.025"
double decimal = Double.parseDouble(s);// 0.025
int num = (int)number; // 234
System.out.println(decimal + " " + num); //0.025 234
As RGO stated, you can do that and also round the decimal number in order to get the appropriate value. Ex:
double number = 20.57;
int integer = (int)number;
double decimal = (10 * number - 10 * integer)/10;
double temp = Math.round(decimal*100.0)/100.0;
System.out.println("Int = " + integer + "\nDecimal = " + temp);
You could do a String split(...). And then Integer parseInt(...) to get back the two integer components.
This is because double
s 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 double
s 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 - double
s cannot provide it - and you should use a library if this is the case.