# precision lost

Suppose I have two double values that I wanna compare them for equality. How can I lose the precision so that it returns true once all numbers before the dot are equal (ignoring the decimal)? I cant conver them to int becuz it reports double value cannot be dereferenced error.

###### Who is Participating?

Commented:
Try to convert it to float and then cast it to int:

double d = 1.2345;
float f = new Double(d).floatValue();
System.out.println((int) f);
0

Software engineerCommented:
>> I cant conver them to int becuz it reports double value cannot be dereferenced error.
???

Can you give you code snippet?
0

Commented:
java.lang.Math.round()

long a = Math.round( 10.0001 );
0

Commented:
...although you should be able to cast a double to int.
0

Commented:
I think he wasn't using the cast...
0

Software engineerCommented:
double d1 = 1.2345;
double d2 = 1.5432;
Double dOne = new Double(d1);
Double dTwo = new Double(d2);
int i1 = (int)dOne.doubleValue();
int i2 = (int)dTwo.doubleValue();
System.out.println("i1=" + i1 + " - i2=" + i2);

Nicely prints:
i1=1 - i2=1
0

Software engineerCommented:
And this too:

double d1 = 1.2345;
double d2 = 1.5432;
int i1 = (int)d1;
int i2 = (int)d2;
System.out.println("i1=" + i1 + " - i2=" + i2);
0

Commented:
if ((int)d1 == (int)d2) {
// do it
}
0

Commented:
Sorry, meant to say Math.floor(), as Math.round() may round up as well as down, but Math.floor() will return the lower, even when Math.round() goes up (e.g. for 1.51 Math.round() returns 2, Math.floor() returns 1).

So...

double a = 1.2;
double b = 1.51;
System.out.println( "a = " + Math.floor( a ) );
System.out.println( "b = " + Math.floor( b ) );

will print:

a = 1
b = 1

cleaner than wrapping, and casting...

btw, zzynx, why do you need the Double object, as the call to doubleValue() simply returns the "double" primitive - you should have just cast "d1" and "d2" directly....
0

Commented:
oops, sorry, zzynx, forgot to refresh before submit...
0

Software engineerCommented:
>> zzynx, why do you need the Double object
When question athours talk about "a double" you're never sure if it is a Double object or a double.
That's why I gave it for both situations.
0

Software engineerCommented:
athours = authors
0

Software engineerCommented:
jtcy, can you explain why you choose that comment instead of the more "intuitive"/"logical"

int i = (int)dOne.doubleValue();

?
0

Commented:
:)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.