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?
The floatValue() method returns the double value converted to type 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With