Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - convert double to float

Tags:

java

I've seen an example where the following code is used to convert a double to a float:

Double.valueOf(someDouble).floatValue()

I would just do it like

(float)someDouble

Is there any advantage to using the former?

like image 210
0ne_Up Avatar asked Feb 08 '17 09:02

0ne_Up


People also ask

Can I convert double to float in Java?

The floatValue() method returns the double value converted to type float .

How do you turn a double into a float?

Using TypeCasting to Convert Double to Float in JavaTo define a float type, we must use the suffix f or F , whereas it is optional to use the suffix d or D for double. The default value of float is 0.0f , while the default value of double is 0.0d . By default, float numbers are treated as double in Java.


1 Answers

Looking at the implementation of Double's floatValue() :

/**
 * Returns the value of this {@code Double} as a {@code float}
 * after a narrowing primitive conversion.
 *
 * @return  the {@code double} value represented by this object
 *          converted to type {@code float}
 * @jls 5.1.3 Narrowing Primitive Conversions
 * @since JDK1.0
 */
public float floatValue() {
    return (float)value;
}

It looks like it behaves exactly like your casting. Therefore there's no advantage to using it.

like image 112
Eran Avatar answered Oct 09 '22 00:10

Eran