为什么我不能将数字转换为双精度数? [英] Why can't I convert a Number into a Double?
问题描述
权重
是一个字段( Firestore ),设置为 100
。
weight
is a field (Number in Firestore), set as 100
.
int weight = json['weight'];
double weight = json['weight'];
int weight
效果很好,返回 100
符合预期,但双重权重
崩溃( Object.noSuchMethod
异常),而不是返回我期望的 100.0
。
int weight
works fine, returns 100
as expected, but double weight
crashes (Object.noSuchMethod
exception) rather than returning 100.0
, which is what I expected.
但是,以下方法有效:
num weight = json['weight'];
num.toDouble();
推荐答案
解析 100时来自Firestore的code>(实际上不支持数字类型,但对其进行转换),则通常会将其解析为
int
。
Dart 不会自动智能转换这些类型。实际上,您不能将 int
转换为 double
,这是您面临的问题。
When parsing 100
from Firestore (which actually does not support a "number type", but converts it), it will by standard be parsed to an int
.
Dart does not automatically "smartly" cast those types. In fact, you cannot cast an int
to a double
, which is the problem you are facing. If it were possible, your code would just work fine.
相反,您可以自己解析:
double weight = json['weight'].toDouble();
铸造
同样有效的是将JSON解析为 num
,然后将其分配给 double
,这将转换为 num
到两倍
。
Casting
What also works, is parsing the JSON to a num
and then assigning it to a double
, which will cast num
to double
.
double weight = json['weight'] as num;
乍一看似乎有点奇怪,实际上 Dart分析工具(例如内置于VS Code和IntelliJ的Dart插件中)会将其标记为不必要的强制转换 ,不是。
This seems a bit odd at first and in fact the Dart Analysis tool (which is e.g. built in into the Dart plugin for VS Code and IntelliJ) will mark it as an "unnecessary cast", which it is not.
double a = 100; // this will not compile
double b = 100 as num; // this will compile, but is still marked as an "unnecessary cast"
double b = 100 num
会进行编译,因为 num
是 double
显式投射将是以下内容:
double b = 100 as num
compiles because num
is the super class of double
and Dart casts super to sub types even without explicit casts.
An explicit cast would be the follwing:
double a = 100 as double; // does not compile because int is not the super class of double
double b = (100 as num) as double; // compiles, you can also omit the double cast
Here is a nice read about "Types and casting in Dart".
您发生了什么事?
double weight;
weight = 100; // cannot compile because 100 is considered an int
// is the same as
weight = 100 as double; // which cannot work as I explained above
// Dart adds those casts automatically
这篇关于为什么我不能将数字转换为双精度数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!