Dart 四捨五入を行う

Dart 四捨五入を行う

Dartで、四捨五入を行うコードを記述してます。「 round 」で可能です。数値以外に使用するとエラーとなります。

環境

  • OS windows11 home
  • Dart 2.18.4

四捨五入

四捨五入するには、「 round 」を使用します。

数値.round()

実際に、使用してみます。

void main() {

  print(1.49.round()); // 1
  print(1.5.round()); // 2

  print(-1.49.round()); // -1
  print(-1.5.round()); // -2

}

実行結果を見ると、四捨五入されていることが確認できます。

数値以外

数値以外を指定するとエラーが発生します。

void main() {

  print('1.49'.round()); 
  // Error: The method 'round' isn't defined for the class 'String'.
  // Try correcting the name to the name of an existing method, or defining a method named 'round'.

}