Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 61 ยท Types and Operators

Numbers: int and double

Learn Dart's number types: int and double, num, division with / and ~/, the modulo operator, parsing text, rounding, formatting and the dart:math library.

Dart has two number types you will use every day: int for whole numbers and double for numbers with a fractional part. Both are objects with methods, so 42.isEven and 3.7.round() are normal code. The details that trip people up are small but important: how division behaves, what % does with negative numbers, how to turn text into a number safely, and why 0.1 + 0.2 is not exactly 0.3.

The Dart code below is read-only; runnable TypeScript stand-ins show the same rules. Where the two languages behave differently, the lesson says so.

int and double

An int is a whole number. On the Dart VM and in native builds it is a 64-bit signed integer, so it ranges from about -9.2 quintillion to +9.2 quintillion. A double is a 64-bit IEEE 754 floating-point number, the same format JavaScript uses for every number.

DART
void main() {
  int apples = 12;
  double price = 0.75;
  var total = apples * price;   // int * double gives double

  print(total);                 // 9.0
  print(apples.runtimeType);    // int
  print(total.runtimeType);     // double
}

Literals decide the type: 7 is an int, 7.0 and 1e3 are doubles. Hexadecimal literals such as 0xFF are ints. A whole-number literal can initialize a double variable (double d = 5; makes 5.0), but a double can never be assigned to an int variable without an explicit conversion.

Above both types sits num, the common supertype. Use it when a function accepts either:

DART
num bigger(num a, num b) => a > b ? a : b;

void main() {
  print(bigger(3, 7));       // 7
  print(bigger(2.5, 1));     // 2.5
}

On the web, Dart compiled to JavaScript stores int values in JavaScript numbers, so integers above 2^53 lose precision. Native Dart (the VM, Flutter on devices, dart compile exe) has full 64-bit integers.

Arithmetic and the division trap

The usual operators work: +, -, *, / and %. There is also ~/, integer division. The two division operators behave differently, and this is the first place Dart surprises people:

DART
void main() {
  print(7 / 2);     // 3.5   (/ always returns a double)
  print(6 / 2);     // 3.0   (even when the result is whole)
  print(7 ~/ 2);    // 3     (~/ truncates toward zero, returns an int)
  print(-7 ~/ 2);   // -3
}

The single slash always gives a double. If you need an integer result, use ~/. Trying int half = 6 / 2; is a compile error, because a double does not fit into an int.

The modulo operator

% gives the remainder, but Dart's version is a Euclidean modulo: the result is never negative, which suits things like wrapping an index around a list. If you want the remainder with the sign of the dividend (as in C, Java and JavaScript), call .remainder():

DART
void main() {
  print(7 % 3);               // 1
  print(-7 % 3);              // 2   (never negative)
  print((-7).remainder(3));   // -1  (sign follows the dividend)
}
TypeScript Division and modulo rules (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Useful members

Both types carry handy members. The commonly used ones are:

Member Example Result
isEven, isOdd 10.isEven true
abs() (-5).abs() 5
sign (-3.2).sign -1.0
isNaN, isInfinite (0 / 0).isNaN true
clamp(lo, hi) 15.clamp(0, 10) 10
compareTo(other) 3.compareTo(5) -1
isNegative (-0.5).isNegative true
floor(), ceil(), round(), truncate() (2.5).ceil() 3
gcd(other) (int) 12.gcd(18) 6

Operators bind as in maths: *, /, %, ~/ before + and -. Compound forms +=, -=, *=, /=, ~/=, %= and the increments ++ and -- exist as well.

Rounding and converting

Rounding methods all return an int:

DART
void main() {
  print(3.7.round());     // 4
  print(2.5.round());     // 3   (halves round away from zero)
  print((-2.5).round());  // -3
  print(3.7.floor());     // 3
  print(3.2.ceil());      // 4
  print((-3.7).truncate()); // -3
  print(3.7.toInt());     // 3   (same as truncate)
  print(5.toDouble());    // 5.0
}

To print a fixed number of decimals, use toStringAsFixed, which returns a String:

DART
void main() {
  var price = 19.5;
  print(price.toStringAsFixed(2));   // 19.50
  print(3.14159.toStringAsFixed(1)); // 3.1
  print(1234.5678.toStringAsPrecision(6)); // 1234.57
}

Calling round() on double.nan or an infinity throws an UnsupportedError, so check isFinite if your data might contain them.

Parsing text into numbers

User input and files arrive as strings. Convert them with int.parse and double.parse, which throw a FormatException on bad input, or with the tryParse variants, which return null instead:

DART
void main() {
  print(int.parse('42'));            // 42
  print(double.parse('3.5'));        // 3.5
  print(int.tryParse('abc'));        // null
  print(int.tryParse('12') ?? 0);    // 12
  print(int.tryParse('x') ?? 0);     // 0
  print(int.parse('ff', radix: 16)); // 255
}

tryParse is almost always the better choice for untrusted text, because a missing value is an ordinary result, not an exception. The ?? operator, covered in null safety, supplies a fallback.

TypeScript A safe parser (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Floating-point surprises

Because double is binary floating point, some decimal fractions cannot be stored exactly:

DART
void main() {
  print(0.1 + 0.2);            // 0.30000000000000004
  print(0.1 + 0.2 == 0.3);     // false
  print((0.1 + 0.2 - 0.3).abs() < 1e-9);  // true: compare with a tolerance
}

This is not a Dart bug; every language with IEEE doubles behaves the same way. Compare doubles with a small tolerance, and for money store whole cents in an int instead of dollars in a double.

The dart:math library

Common maths functions live in the dart:math library, which you import:

DART
import 'dart:math';

void main() {
  print(sqrt(81));            // 9.0
  print(pow(2, 10));          // 1024
  print(max(3, 8));           // 8
  print(min(3, 8));           // 3
  print(pi);                  // 3.141592653589793
  print(Random().nextInt(6)); // a random 0..5
}

sqrt returns a double. pow(2, 10) returns a num; with integer arguments the result is an int. Other functions include sin, cos, atan2, log (natural log) and exp. Random produces pseudo-random values; Random.secure() should be used for anything security-related.

flowchart TD
    N["num"] --> I["int<br/>whole numbers"]
    N --> D["double<br/>floating point"]

Both int and double are subtypes of num. A function that takes num accepts either.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does print(9 / 3); output in Dart?

    The / operator always returns a double, so 9 / 3 is 3.0. Use ~/ to get an int.
  2. 2. What is the value of -7 % 3 in Dart?

    Dart's % is a Euclidean modulo and never returns a negative result, so -7 % 3 is 2. (-7).remainder(3) gives -1.
  3. 3. Which call returns null instead of throwing when the text is not a number?

    tryParse returns null for invalid input. The parse methods throw a FormatException.
  4. 4. Why is 0.1 + 0.2 == 0.3 false?

    Binary floating point cannot represent 0.1 or 0.2 exactly, so the sum differs slightly from 0.3. Compare with a tolerance.

Summary

  • int holds whole numbers, double holds floating-point numbers, and num is their shared supertype.
  • / always returns a double; ~/ is truncating integer division; % never returns a negative value, while remainder() keeps the dividend's sign.
  • round, floor, ceil and truncate return an int; toStringAsFixed formats decimals as text.
  • Prefer int.tryParse and double.tryParse for untrusted text.
  • Compare doubles with a tolerance, and use whole cents for money. Import dart:math for sqrt, pow, min, max and Random.

Next, work with text in Strings and String Interpolation.