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.

  • double

  • 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:

  1. var x = 1;
  2. var hex = 0xDEADBEEF;

If a number includes a decimal, it is a double. Here are some examplesof defining double literals:

  1. var y = 1.1;
  2. var exponents = 1.42e5;

As of Dart 2.1, integer literals are automatically converted to doubleswhen necessary:

  1. 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:

  1. // String -> int
  2. var one = int.parse('1');
  3. assert(one == 1);
  4. // String -> double
  5. var onePointOne = double.parse('1.1');
  6. assert(onePointOne == 1.1);
  7. // int -> String
  8. String oneAsString = 1.toString();
  9. assert(oneAsString == '1');
  10. // double -> String
  11. String piAsString = 3.14159.toStringAsFixed(2);
  12. assert(piAsString == '3.14');

The int type specifies the traditional bitwise shift (<<, >>), AND(&), and OR (|) operators. For example:

  1. assert((3 << 1) == 6); // 0011 << 1 == 0110
  2. assert((3 >> 1) == 1); // 0011 >> 1 == 0001
  3. 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.

  1. const msPerSecond = 1000;
  2. const secondsUntilRetry = 5;
  3. const msUntilRetry = secondsUntilRetry * msPerSecond;