我想把1或32.23这样的字符串解析为整数和双精度数。我怎么能和达特在一起?


当前回答

void main(){
String myString ='111';
int data = int.parse(myString);
print(data);
}

其他回答

 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()在无法解析String时抛出错误

你可以这样做,这样更容易转换

示例代码

void main() {
  var myInt = int.parse('12345');
 var number = myInt.toInt();
  print(number); // 12345
  print(number.runtimeType);  // int
  
  
    var myDouble = double.parse('123.45');
  var double_int = myDouble.toDouble();
  print(double_int); // 123.45
   print(double_int.runtimeType);  
}

如果你不知道你的类型是string还是int,你可以这样做:

int parseInt(dynamic s){
  if(s.runtimeType==String) return int.parse(s);
  return s as int;
}

双:

double parseDouble(dynamic s){
  if(s.runtimeType==String) return double.parse(s);
  return s as double;
}

因此你可以使用parseInt('1')或parseInt(1)

将字符串转换为Int

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

将字符串转换为Double

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

在DartPad中的例子

String age = stdin.readLineSync()!; // first take the input from user in string form
int.parse(age);  // then parse it to integer that's it