2012年4月23日月曜日

文字列と数値を変換する

このエントリーをはてなブックマークに追加
Dartで文字列(String)と数値(num)を変換するには次のようにします。

文字列から数値を得る

整数(int)を得る場合はMath.parseInt、小数を得る場合には Math.parseDouble を使います。サンプルコード
main() {
  int i = Math.parseInt("123");
  double d = Math.parseDouble("1.23");
  print("i=$i, d=$d");
}
変換に失敗するとBadNumberFormatException例外が発生します。

数値リテラルとして表現可能な文字列が変換可能なようですので、次のような変換もできます。サンプルコード
main() {
  // 大きな数(1e+30)
  print(Math.parseInt("1000000000000000000000000000000"));
  // 16進数(10)
  print(Math.parseInt("0xA"));
  // 指数表現(10)
  print(Math.parseDouble("1e+1"));
}

数値から文字列を得る

単純に文字列リテラルとして、あるいはtoStringメソッドで変換できます。
main() {
  int i = 1;
  print("$i, ${i.toString()}"); // 1, 1
}
書式を指定するにはnumクラスに用意されている次のメソッドを使います。

toRadixString
指定の進数の文字列
toStringAsExponential
指定した指数値を持つ文字列
toStringAsFixed
指定桁数の小数部を持つ文字列
toStringAsPrecision
指定精度の文字列

サンプルコード
void main() {
  print("123=${123.toRadixString(10)}(10)"); // 123(10)
  print("123=${123.toRadixString(16)}(16)"); // 7b(16)
  print("123=${123.toStringAsExponential(1)}"); // 1.2e+2
  print("123=${123.toStringAsExponential(2)}"); // 1.23e+2
  print("123=${123.toStringAsExponential(3)}"); // 1.230e+2
  print("123.45=${(123.45).toStringAsFixed(1)}"); // 123.5
  print("123.45=${(123.45).toStringAsFixed(2)}"); // 123.45
  print("123.45=${(123.45).toStringAsFixed(3)}"); // 123.450
  print("123.45=${(123.45).toStringAsPrecision(2)}"); // 1.2e+2
  print("123.45=${(123.45).toStringAsPrecision(3)}"); // 123
  print("123.45=${(123.45).toStringAsPrecision(4)}"); // 123.5
}

0 件のコメント:

コメントを投稿