Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Better way to convert Double object to float

Tags:

java

casting

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 Answers

The Double class has a floatValue() property.

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

function(fakePi.floatValue());
like image 145
Jesse Bethke Avatar answered Mar 05 '26 00:03

Jesse Bethke