Dart comes with several built-in libraries that you can leverage to implement various features, including a dedicated library for mathematical operations.
import 'dart:math';Code language: JavaScript (javascript)
Common Constants
print(pi); // 3.141592653589793 Pi
print(e); // 2.718281828459045 Euler's number
print(sqrt2); // √2 ≈1.4142Code language: PHP (php)
Trigonometric Functions
sin() cos() tan() Parameters: radians. Degrees ↔ Radians conversion: radians = degrees × pi / 180
void trigDemo() {
assert(cos(pi) == -1.0);
int degrees = 30;
double radians = degrees * pi / 180;
double result = sin(radians);
// Never compare floating-point numbers directly with ==, check absolute difference
assert((result - 0.5).abs() < 0.01);
}Code language: Dart (dart)
Maximum / Minimum Values
assert(max(1, 1000) == 1000);
assert(min(1, -1000) == -1000);
Random Numbers with Random
void randomDemo() {
final rand = Random();
double d = rand.nextDouble(); // [0.0, 1.0)
int i = rand.nextInt(10); // 0 ~ 9
bool b = rand.nextBool(); // true / false
// Cryptographically secure random for passwords and keys
final secureRand = Random.secure();
}Code language: Dart (dart)
Frequently Used Functions
sqrt(9); // Square root, returns 3.0
pow(2, 3); // Exponentiation 2^3=8.0
log(e); // Natural logarithm
atan2(y, x); // Arctangent, widely used to calculate angles in coordinate systemsCode language: Dart (dart)
Full Example
import 'dart:math';
void main() {
// Constants
print('pi = $pi');
print('e = $e');
// Trigonometric functions
final rad30 = 30 * pi / 180;
print('sin30° = ${sin(rad30)}');
// max min
print('max(2,9) = ${max(2,9)}');
print('min(2,9) = ${min(2,9)}');
// Random values
final r = Random();
print('Random integer 0~9:${r.nextInt(10)}');
print('[0,1) floating point:${r.nextDouble()}');
print('Random boolean:${r.nextBool()}');
}Code language: Dart (dart)
Run the Example
D:\dartdemo\firstdart>dart run
Building package executable...
Built firstdart:firstdart.
pi = 3.141592653589793
e = 2.718281828459045
sin30° = 0.49999999999999994
max(2,9) = 9
min(2,9) = 2
Random integer 0~9:9
[0,1) floating point:0.08331912429354282
Random boolean:falseCode language: JavaScript (javascript)
The dart:math Library
Previous: Class Modifiers
Next: The dart:convert Library