如何使用 Dart 将字符串解析为数字? [英] How do I parse a string into a number with Dart?

查看:176
本文介绍了如何使用 Dart 将字符串解析为数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将诸如 132.23 之类的字符串解析为整数和双精度数.我怎样才能用 Dart 做到这一点?

I would like to parse strings like 1 or 32.23 into integers and doubles. How can I do this with Dart?

推荐答案

您可以使用 int.parse() 将字符串解析为整数.例如:

You can parse a string into an integer with int.parse(). For example:

var myInt = int.parse('12345');
assert(myInt is int);
print(myInt); // 12345

注意 int.parse() 接受 0x 前缀字符串.否则,输入将被视为 base-10.

Note that int.parse() accepts 0x prefixed strings. Otherwise the input is treated as base-10.

您可以使用 double.parse() 将字符串解析为双精度值.例如:

You can parse a string into a double with double.parse(). For example:

var myDouble = double.parse('123.45');
assert(myDouble is double);
print(myDouble); // 123.45

parse() 如果无法解析输入,将抛出 FormatException.

parse() will throw FormatException if it cannot parse the input.

这篇关于如何使用 Dart 将字符串解析为数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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