Dartで文字列を数値に解析するにはどうすればよいですか?


105

「1」や「32.23」などの文字列を整数と倍精度数に解析したいと思います。Dartでこれを行うにはどうすればよいですか?

回答:


175

で文字列を整数に解析できますint.parse()。例えば:

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

接頭辞付きの文字列をint.parse()受け入れることに注意してください0x。それ以外の場合、入力はbase-10として扱われます。

を使用すると、文字列をdoubleに解析できますdouble.parse()。例えば:

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

parse() 入力を解析できない場合は、FormatExceptionをスローします。


後で無効な文字を含む文字列から整数をどのように解析する必要がありますか?たとえば、-1を取得したい場合は「-01:00」、172を取得したい場合は「172リンゴ」。JavaScriptではparseInt( "-01:00")は問題なく動作しますが、Dartはエラーを返します。文字ごとに手動でチェックしないで簡単な方法はありますか?ありがとう。
user1596274


4

ダート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 ...
  //
}

3
 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()は、文字列を解析できなかった場合にエラーをスローする可能性があります


2
int.parse()またdouble.parse()、文字列を解析できなかった場合は、エラーをスローする可能性があります。他の人がダーツをよりよく理解して理解できるように、回答を詳しく説明してください。
josxha

1
josxhaについて言及していただきありがとうございます。私はダートの完全な初心者であり、他の人を助けるために全力を尽くしています。
Rajdeep12345678910

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.