【Dart】文字列(String)と数値(num)を相互変換

Dartで文字列(String)と数値(num)を相互に変換する方法についてソースコード付きでまとめました。

スポンサーリンク

【キャスト】文字列(String) → 数値(Int, Double)

文字列から整数(int)に変換する場合はMath.parseInt、小数(Double)に変換する場合は Math.parseDoubleを使います。

int numInt = Math.parseInt("123");
double numDOuble = Math.parseDouble("1.23");

※文字列が数値に変換できないものだと「BadNumberFormatException例外」が発生します。

スポンサーリンク

【キャスト】数値(Int, Double) → 文字列(String)

数値(Int, Double)から文字列(String)に変換する場合はtoStringメソッドを使います。

int num = 1;
Stirng str = num.toString();

以下のメソッドを使えば、書式を指定して文字列を変換できます。

メソッド 書式
toRadixString 指定の進数の文字列
toStringAsExponential 指定した指数値を持つ文字列
toStringAsFixed 指定桁数の小数部を持つ文字列
toStringAsPrecision 指定精度の文字列
void main() {
  int num = 123;
  double num = 123.45;

  print(num.toRadixString(10)); // 123 (10進数)
  print(num.toRadixString(16); // 7b (16進数)
  print(num.toStringAsExponential(1)); // 1.2e+2
  print(num.toStringAsExponential(2)); // 1.23e+2
  print(num.toStringAsExponential(3)); // 1.230e+2
  print(num2.toStringAsFixed(1)); // 123.5
  print(num2.toStringAsFixed(2)); // 123.45
  print(num2.toStringAsFixed(3)); // 123.450
  print(num2.toStringAsPrecision(2)); // 1.2e+2
  print(num2.toStringAsPrecision(3)); // 123
  print(num2.toStringAsPrecision(4)); // 123.5
}
【Flutter入門】iOS、Android、Windowsアプリ開発
FlutterによるiOS、Android、Windowsアプリ開発について入門者向けに紹介します。
【Dart入門】基礎文法とサンプルコード集
Dartの基礎文法とサンプルコードについて入門者向けにまとめました。
Dart
スポンサーリンク

コメント