3

Suppose I'm given a Double object d and a function that takes in a primitive float, is there a better way to pass on object do to the function than by double casting?

Double fakePi = 3.14  
void function(float num) {}

function(fakePi): Returns a compiling error as function does not take Double object as argument

function((float) fakePi): Returns a compiling error as Double cannot be converted to a float

function((float) (double) fakePi): Compiles and runs without error

Although this works, my instincts tells me that there are better ways to do this and that I should avoid doing multiple type castings, especially since float, double, Double are closely related to each other.

1
  • 1
    Try fakePi.floatValue(). Always consult the documentation when in doubt. Commented Sep 14, 2014 at 22:15

1 Answer 1

5

The Double class has a floatValue() property.

http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html

function(fakePi.floatValue());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.