Dart tryParse double与double字符串 [英] Dart tryParse double vs string of double

查看:77
本文介绍了Dart tryParse double与double字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Dart中使用tryParse的方式似乎有些不一致,或者我正在以一种愚蠢的方式来解决它,很可能是后者.

There seems to be some inconsistency with the way tryParse is used in Dart or I'm going about it a silly way, likely the latter.

当我们使用int.tryParse语句时,如果将它作为双精度值传递给10.0,则我们希望得到10个值.

When we use the int.tryParse statement, if we pass it 10.0 as a double, we would expect to get 10 which we do.

print(int.tryParse(10.0.toString())); ==> 10

如果我们将其10.0作为字符串传递,它将返回null.

If we pass it 10.0 as a string, it will return null.

print(int.tryParse('10.0')); ==> null

我发现这有点奇怪,因为我本以为10.0.toString()相当于"10.0".有人有解释吗?

I find this a bit strange as I would have thought 10.0.toString() is equivalent to '10.0'. Does anyone have an explanation?

推荐答案

Web编译器和本机代码之间的区别.

The difference is between web compiler and native code.

将Dart编译到网络(转换为JavaScript)时,所有数字均为JavaScript数字,这实际上意味着加倍.这意味着整数10和双精度10.0是同一对象.只有"10"个JavaScript中的值.因此,当您对该值进行 toString 时,它必须选择,并且会选择"10.0&" 上的"10" .

When Dart is compiled to the web (to JavaScript), all numbers are JavaScript numbers, which effectively means doubles. That means that the integer 10 and the double 10.0 is the same object. There is only on "10" value in JavaScript. So, when you do toString on that value, it has to choose, and it chooses "10" over "10.0".

在本地运行时,双精度10.0和整数10是两个不同的对象,它们的 toString "10.0." "10"; .

When run natively, the double 10.0 and the integer 10 are two different objects, and their toStrings are "10.0" and "10" respectively.

int.tryParse 函数不接受"10.0." 作为输入,这就是为什么它返回 null 的原因.因此,当在网络上(包括dartpad.dev)进行测试时, int.tryParse(10.0.toString())成功,因为 toString "10".,并且在本地测试时,相同的代码会给出 null ,因为 toString "10.0." .

The int.tryParse function does not accept "10.0" as input, which is why it returns null. So, when testing on the web (including dartpad.dev), int.tryParse(10.0.toString()) succeeds because the toString is "10", and when testing natively the same code gives null because the toString is "10.0".

这篇关于Dart tryParse double与double字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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