为什么我不能将数字转换为双精度数? [英] Why can't I convert a Number into a Double?

查看:201
本文介绍了为什么我不能将数字转换为双精度数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

权重是一个字段( 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时(实际上不支持数字类型,但对其进行转换),则通常会将其解析为 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-class.html rel = noreferrer> double 和Dart甚至在没有显式转换的情况下也将超级转换为子类型。

显式投射将是以下内容:

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

这是关于 Dart中的类型和类型转换 的不错的读物。 >。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆