当前位置: 首页 > 知识库问答 >
问题:

为什么我不能把一个数转换成双数?

沃瑾瑜
2023-03-14
int weight = json['weight'];
double weight = json['weight'];
num weight = json['weight'];
num.toDouble();

共有1个答案

南宫喜
2023-03-14

当从Firestore解析100时(它实际上不支持“数字类型”,但将其转换),按照标准,它将被解析为int
Dart不会自动“巧妙地”强制转换这些类型。事实上,您不能将int强制转换为double,这就是您面临的问题。如果可能的话,您的代码就可以正常工作了。

相反,您可以自己解析它:

double weight = json['weight'].toDouble();

同样有效的方法是将JSON解析为num,然后将其分配给double,后者将num强制转换为double

double weight = json['weight'] as num;
double a = 100; // this will not compile

double b = 100 as num; // this will compile, but is still marked as an "unnecessary cast"
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
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
 类似资料:
  • 问题内容: Java中的所有数字都应为int类型。以下行在Java> 1.5中是合法的 同样的机制去和实例。但是龙的作品完全不同。以下代码给出了编译时错误 Long对长类型使用自动装箱方法,因此 我看不到为什么不能将int赋给Long变量。关于这个问题有什么想法吗? 问题答案: 我认为问题不在于泛型转换原语和包装。问题是关于将int转换为java.lang.Long和将int转换为java.lan

  • 谁能告诉我从.p12文件中提取/转换证书.crt文件的正确方法/命令吗?在我搜查之后。我找到了将.pem转换为.crt的方法。但未找到.p12到.crt。

  • 问题内容: 您可以将int隐式转换为double: 您可以将int显式转换为double: 您可以将double显式转换为int: 为什么不能将一个double隐式转换为int? : 问题答案: 的范围比宽。这就是为什么您需要显式强制转换。由于相同的原因,您不能隐式地从转换为:

  • 我正试图从图中的窗体向表插入子层,但为什么不能使用where呢?

  • 这应该很容易完成,但是当我尝试将字符串转换为整数时,这些命令返回错误: Android monitor返回以下错误: 提前致谢

  • 问题内容: 我有一个WSDL文件,我需要将其转换为Java,为此,我使用下面链接中的分步过程 http://axis.apache.org/axis2/java/core/tools/eclipse/wsdl2java- plugin.html 就像将axis2 codegen jar文件添加到eclipse文件夹中的dropins文件夹中并重新启动eclipse一样,但是我在eclipse ID