> hey
> how can i rturn the fractional and the integral part
There are a variety of ways, from mathematical approaches to string manipulation. I'll bet if you search this forum and/or the web, you'll see that this question has been asked numerous times before. Try searching for this first; if you've tried something and it's not working out, post what you've tried and what it is you're confused about.
Good luck!
Like Learnable suggested:
double num = 321654.652;
double integral = (double)((int)num);
double fractional = num-integral;
.
I suspect a double-error-rounding-question next...
; )
import java.math.*;
public class DoubleSeparation {
public DoubleSeparation() {
}
public static void main(String[] args)
{
BigDecimal b = new BigDecimal("321654.652");
int n = b.intValue();
b = b.subtract(new BigDecimal(n));
BigDecimal bb = new BigDecimal(b.intValue());
while(!b.equals(bb))
{
b = b.multiply(new BigDecimal(10));
b = b.setScale(b.scale() - 1);
bb = new BigDecimal(b.intValue());
}
System.out.println(n + " " + b);
}
}
Or just use a String.
public class DoubleSeparation {
public DoubleSeparation() {
}
public static void main(String[] args)
{
double d = 321654.652;
String s = Double.toString(d);
int n = s.indexOf('.');
String c = s.substring(0, n);
String m = s.substring(n+1, s.length());
int in = Integer.parseInt(c);
int fr = Integer.parseInt(m);
System.out.println(in + " " + fr);
}
}
> Or just use a String.
> > public class DoubleSeparation {
...
> }
Now try the same with "double d = 0.000001;"
Hint: You will need DecimalFormat if you want to use Strings.
> Now try the same with "double d = 0.000001;"
>
> Hint: You will need DecimalFormat if you want to use
> Strings.
To preserve the representation of the mantissa, you will have to use either BigDecimal or DecimalFormat. The mantissa has to be represented by a String. Here is the implementation using BigDecimal.import java.math.*;
public class DoubleSeparation {
public DoubleSeparation() {
}
public static void main(String[] args)
{
BigDecimal b = new BigDecimal("0.00000001");
long c = b.longValue();
b = b.subtract(new BigDecimal(c));
int s = b.toString().length();
String m = "";
if(s >= 2)
m = b.toString().substring(2, s);
System.out.println(c + " " + m);
}
}
thank you all
but i have 1 comment , your are casting or parsing to int or long ..
but i think by this way it could be possible of losing some data because
double hold more than long or int example
if you cast 321654987321654987321654987321654987.123456
to int ?