Java,不可能将 Object 转换为 Float...为什么?
为什么这有效:
Object prova = 9.2;
System.out.println(prova);
Double prova2 = (Double) prova;
System.out.println(prova2);
但这不起作用?
Object prova = 9.2;
System.out.println(prova);
Float prova2 = (Float) prova;
System.out.println(prova2);
我在我的java android应用程序中损失了1个小时,所以我不得不将它转换为双精度,然后将双精度转换为浮点数,否则我有一个异常
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
因为你在编写时依赖于自动装箱
如果你希望它是一个 Float,请尝试
记住 java.lang.Float 和 java.lang.Double 是同级类型;常见类型是 java.lang.Number
如果您想以任何格式表达数字,请使用 API,例如 Number.floatValue()
Because you are relying on autoboxing when you wrote
If you want it to be a Float, try
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()
因为
prova
是Double
,而Double
不是Float
的子类型。您可以从浮点文字开始:
9.2f
(在这种情况下,prova
实际上是一个Float
),或者您可以像这样:Because
prova
is aDouble
, andDouble
is not a subtype ofFloat
.Either you could start with a float literal:
9.2f
(in which caseprova
would actually be aFloat
) or, you could it like this:9.2
是一个双重文字。请尝试使用9.2f
。错误消息(您可能应该将其包含在您的问题中)也很好地解释了它:
9.2
is a double literal. Try9.2f
instead.The error message (which you probably should have included in your question) explains it quite well also:
因为如果你不指定,它将是一个双精度。如果你希望它是一个浮动,你需要
Because if you don't specify, it will be a double. If you want it to be a float, you need
尝试将其转换为 Float 而不是 float
简单的
Try Casting it as Float not float
Simple
嗨,我也遇到了这个问题,我花了很长时间才想出这个非常简单的解决方案。
对于遇到此问题的任何其他人,并且您可能不想或无权更改您正在接收的对象,转换对象值的另一种方法是首先将 Double 值转换为 double 变量类型。然后简单地将 double 转换为 float... 示例:(
我还没有测试过这个,但根据最初发布的问题做了这个)
(这是我自己使用的一个示例,希望这些示例将来可以帮助其他人)
对我来说以前当我尝试使用时出现错误:
Hi I hit this problem too and it took me a very long time to come up with this very simple solution.
For anyone else who hits this problem and you may not want to or have access to changing the object you are receiving, an alternative to converting object values is to first convert your Double value to a double variable type. Then simply cast double to float... Examples:
(I have not tested this but made this based on the initial posted problem)
(This is an example that I was working with myself, hope these examples can help others in future)
For me this previously was giving errors when I tried to use: