user11008708
user11008708

Reputation:

How to compare Integer and Double wrapper?

Integer i = 1000;
Double d = 1000.0;

??

Is there a way for me to compare the numerical values in these two wrappers without unwrapping or casting?

I can't use == or .equals() since they compare the reference equality. Neither can I use Integer.compare(i,d) nor i.compareTo(d) since they have different types.

Thank you in advance for answering a newbie question.

edit: changed d.compareTo(i) to i.compareTo(d) since it is a Integer method.

Upvotes: 0

Views: 1650

Answers (4)

silentsudo
silentsudo

Reputation: 6963

Please refer here https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#compare(double,%20double)

you can use Double.compare(param1, param2)

Integer a = 1000;
Double b = 1000.0;
System.out.println(Double.compare(a, b) == 0);

As informed by @Andy this is the actual flow

Integer will be unboxed to int, and then widened to double. There is no conversion from Integer to Double here.

Upvotes: 3

hhrzc
hhrzc

Reputation: 2050

You can use String:

boolean result = ("" + i).equals(("" + d).split("\\.")[0]);

Upvotes: -1

You can try like this but I am not sure it is what you want

d.intValue()

Upvotes: 0

Sarangan
Sarangan

Reputation: 967

You can use :

Double.compare(val1,val2)==0 

if any parameter are not floating point variable, they will be promoted to floating point.

In floating point operation/comparisons, if one argument is floating/double then other one being int is also promoted to the same.

Upvotes: 1

Related Questions