Why this works:
Object prova = 9.2; System.out.println(prova); Double prova2 = (Double) prova; System.out.println(prova2);
And this doesn't?
Object prova = 9.2; System.out.println(prova); Float prova2 = (Float) prova; System.out.println(prova2);
I lost 1 hour in my java android application cause of this thing so i had to cast it in a double and than the double in a float or i had an exception
Type Casting in Java – An IntroductionType Casting is a feature in Java using which the form or type of a variable or object is cast into some other kind or Object, and the process of conversion from one type to another is called Type Casting.
Type casting is a way of converting data from one data type to another data type. This process of data conversion is also known as type conversion or type coercion. In Java, we can cast both reference and primitive data types. By using casting, data can not be changed but only the data type is changed.
Because you are relying on autoboxing when you wrote
Object prova = 9.2;
If you want it to be a Float, try
Object prova = 9.2f;
Remember that java.lang.Float and java.lang.Double are sibling types; the common type is java.lang.Number
If you want to express a Number in whatever format, use the APIs, for example Number.floatValue()
Because prova
is a Double
, and Double
is not a subtype of Float
.
Either you could start with a float literal: 9.2f
(in which case prova
would actually be a Float
) or, you could it like this:
Float prova2 = ((Double) prova).floatValue();
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