Menu
Coddy logo textTech

String を double に変換

CoddyのDartジャーニー「基礎」セクションの一部 — レッスン 84/94。

double.parse() メソッドは、小数点を含む数値の文字列表現を double 値に変換します。

小数を含む文字列を作成:

String priceAsString = '19.99';

double.parse() を使用して文字列を double に変換:

double price = double.parse(priceAsString);
print(price);

上記のコードを実行した後、出力は次のようになります:

19.99

変換された double を計算に使用できます:

String discountAsString = '5.50';
double discount = double.parse(discountAsString);
double finalPrice = price - discount;
print('Final price: $finalPrice');

上記のコードを実行すると、出力は以下のようになります:

Final price: 14.49
challenge icon

チャレンジ

初心者

このチャレンジでは、double.parse() を使用して文字列を double に変換する練習をします。このメソッドは、小数数の文字列表現を double 値に変換します。

コードを完成させて、priceText 文字列を double に変換し、priceValue 変数に格納してください。

チートシート

double.parse() メソッドは、10進数の文字列表現を double 値に変換します。

String priceAsString = '19.99';
double price = double.parse(priceAsString);
print(price); // Output: 19.99

変換された double を計算に使用できます:

String discountAsString = '5.50';
double discount = double.parse(discountAsString);
double finalPrice = price - discount;
print('Final price: $finalPrice'); // Output: Final price: 14.49

自分で試してみよう

void main() {
  // この文字列には価格のテキストが含まれています
  String priceText = "23.50";
  
  // TODO: double.parse() を使用して priceText を double に変換する
  // それを priceValue 変数に格納する
  double priceValue;
  
  // これにより税込み価格 (15%) を計算します
  double priceWithTax = priceValue * 1.15;
  
  // これにより結果を表示します
  print("Original price: \$${priceText}");
  print("Price as a double: ${priceValue}");
  print("Price with 15% tax: \$${priceWithTax.toStringAsFixed(2)}");
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

基礎のすべてのレッスン