如何使用Dart将字符串解析为数字?

时间:2012-10-31 21:11:46

标签: dart

我想将“1”或“32.23”等字符串解析成整数和双精度数。我怎么能用Dart做到这一点?

7 个答案:

答案 0 :(得分:86)

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

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

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

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

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

parse()无法解析输入,则会抛出FormatException。

答案 1 :(得分:42)

在Dart 2中int.tryParse可用。

对于无效输入而不是抛出,它返回null。您可以像这样使用它:

int val = int.tryParse(text) ?? defaultValue;

答案 2 :(得分:7)

 void main(){
  var x = "4";
  int number = int.parse(x);//STRING to INT

  var y = "4.6";
  double doubleNum = double.parse(y);//STRING to DOUBLE

  var z = 55;
  String myStr = z.toString();//INT to STRING
}

int.parse()和double.parse()无法解析字符串时会抛出错误

答案 3 :(得分:6)

根据dart 2.6

已弃用onError的可选int.parse参数。因此,您应该改用int.tryParse

注意double.parse也是如此。因此,请改用double.tryParse

  /**
   * ...
   *
   * The [onError] parameter is deprecated and will be removed.
   * Instead of `int.parse(string, onError: (string) => ...)`,
   * you should use `int.tryParse(string) ?? (...)`.
   *
   * ...
   */
  external static int parse(String source, {int radix, @deprecated int onError(String source)});

区别在于如果源字符串无效,int.tryParse返回null

  /**
   * Parse [source] as a, possibly signed, integer literal and return its value.
   *
   * Like [parse] except that this function returns `null` where a
   * similar call to [parse] would throw a [FormatException],
   * and the [source] must still not be `null`.
   */
  external static int tryParse(String source, {int radix});

因此,在您的情况下,它应类似于:

// Valid source value
int parsedValue1 = int.tryParse('12345');
print(parsedValue1); // 12345

// Error handling
int parsedValue2 = int.tryParse('');
if (parsedValue2 == null) {
  print(parsedValue2); // null
  //
  // handle the error here ...
  //
}

答案 4 :(得分:5)

您可以使用int.parse('your string value');解析字符串。

示例:-int num = int.parse('110011'); print(num); // prints 110011 ;

答案 5 :(得分:1)

将字符串转换为整数

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

将字符串转换为双精度

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

https://dartpad.dev/5bddb5fb077c3f0e63db88c33fdbb1f1? enter image description here

答案 6 :(得分:-1)

以上解决方案不适用于 String,例如:

String str = '123 km';

所以,对我来说适用于所有情况的一行答案是:

int r = int.tryParse(str.replaceAll(RegExp(r'[^0-9]'), '')) ?? defaultValue;
or
int? r = int.tryParse(str.replaceAll(RegExp(r'[^0-9]'), ''));

但请注意,它不适用于以下类型的字符串

String problemString = 'I am a fraction 123.45';
String moreProblem = '20 and 30 is friend';

如果您想提取适用于各种类型的双精度值,请使用:

double d = double.tryParse(str.replaceAll(RegExp(r'[^0-9\.]'), '')) ?? defaultValue;
or
double? d = double.tryParse(str.replaceAll(RegExp(r'[^0-9\.]'), ''));

这适用于 problemString,但不适用于 moreProblem

相关问题