Numbers
Dart numbers come in two flavors:
- int
Integer values no larger than 64 bits,depending on the platform.On the Dart VM, values can be from-263 to 263 - 1.Dart that’s compiled to JavaScript usesJavaScript numbers,allowing values from -253 to 253 - 1.
- 64-bit (double-precision) floating-point numbers, as specified bythe IEEE 754 standard.
Both int
and double
are subtypes of num
.The num type includes basic operators such as +, -, /, and *,and is also where you’ll find abs()
, ceil()
,and floor()
, among other methods.(Bitwise operators, such as >>, are defined in the int
class.)If num and its subtypes don’t have what you’re looking for, thedart:math library might.
Integers are numbers without a decimal point. Here are some examples ofdefining integer literals:
var x = 1;
var hex = 0xDEADBEEF;
If a number includes a decimal, it is a double. Here are some examplesof defining double literals:
var y = 1.1;
var exponents = 1.42e5;
As of Dart 2.1, integer literals are automatically converted to doubleswhen necessary:
double z = 1; // Equivalent to double z = 1.0.
Version note: Before Dart 2.1, it was an error to use an integer literal in a double context.
Here’s how you turn a string into a number, or vice versa:
// String -> int
var one = int.parse('1');
assert(one == 1);
// String -> double
var onePointOne = double.parse('1.1');
assert(onePointOne == 1.1);
// int -> String
String oneAsString = 1.toString();
assert(oneAsString == '1');
// double -> String
String piAsString = 3.14159.toStringAsFixed(2);
assert(piAsString == '3.14');
The int type specifies the traditional bitwise shift (<<, >>), AND(&), and OR (|) operators. For example:
assert((3 << 1) == 6); // 0011 << 1 == 0110
assert((3 >> 1) == 1); // 0011 >> 1 == 0001
assert((3 | 4) == 7); // 0011 | 0100 == 0111
Literal numbers are compile-time constants.Many arithmetic expressions are also compile-time constants,as long as their operands arecompile-time constants that evaluate to numbers.
const msPerSecond = 1000;
const secondsUntilRetry = 5;
const msUntilRetry = secondsUntilRetry * msPerSecond;