Skip to content
Blog

Working with num and Converting Between Integers and Doubles in Dart

num unifies Dart's two number types. Learn / vs ~/ vs %, int.parse and double.parse, toStringAsFixed, and the truncation traps inside toInt().

Published on • December 3, 2026

AI Assistant

Dart has two number types, and most bugs involving them are not about arithmetic — they are about conversions. This post follows num, the supertype that unites integers and doubles, and then walks through every realistic way values cross between the two: division operators, parsing, formatting, and the conversions that quietly truncate instead of rounding.

num: the common supertype of both

Both int and double are subtypes of num, and num is sealed — no type other than int and double may extend or implement it. That seal is what lets the analyzer reason about arithmetic confidently: any num you hold is one of exactly two things at runtime.

void main() {
  num x = 1;      // x can hold both int and double values.
  x += 2.5;       // Now x is 3.5.
  print(x.abs()); // Shared methods live on num.
  num y = 10;
  print(y / 4);   // 2.5 — the / operator returns double.
  print(y.round()); // 10 — rounding lives on num too.
}

The shared surface includes the arithmetic and comparison operators plus abs(), ceil(), floor(), clamp(), isNaN, isFinite and isInfinite. Bitwise operators such as >>, & and | are defined on int alone, and if num and its subtypes do not offer what you need, the dart:math library usually does.

Integer literals promote to double when the context says so

You never write 1.0 just to satisfy a double parameter. An integer literal appearing where a double is expected is automatically converted, because the context type flows into the literal.

void main() {
  double z = 1; // Equivalent to double z = 1.0.
  print(z);     // 1.0
  double half(double value) => value / 2;
  print(half(1)); // 0.5 — the literal arrives as 1.0.
}

The promotion applies to literals only. An existing int variable is an int and stays an int, so widening it requires an explicit toDouble() — there is no implicit narrowing in either direction, and assigning a double to an int variable is a compile-time error.

/ vs ~/ vs %

Three operators, three very different contracts. / always performs floating-point division and always returns a double, even when both operands are integers and the math comes out whole. ~/ performs truncating integer division and returns an int. % computes the Euclidean modulo.

void main() {
  print(7 / 2);   // 3.5 — always double.
  print(7 ~/ 2);  // 3   — truncated toward zero.
  print(7 % 2);   // 1   — Euclidean modulo.
  print(-7 ~/ 2); // -3  — truncates toward zero, not toward negative infinity.
  print(-7 % 2);  // 1   — the result takes the sign of a positive divisor.
  print(7.5 ~/ 2); // 3  — works on doubles too, discarding the fraction.
}

The negative cases are where the surprises hide: ~/ truncates toward zero while floor() moves toward negative infinity, so (-7).floor() is -7 but (-7 ~/ 2) is -3. And because / never yields an integer type, code that needs whole numbers must say so with ~/ or by rounding afterward.

Parsing strings into numbers

int.parse() and double.parse() convert text to numbers, and both throw a FormatException when the text is not a valid literal. When failure is expected, tryParse() returns null instead — the null-safe way to handle user input.

void main() {
  var one = int.parse('1');
  var onePointOne = double.parse('1.1');
  var hex = int.parse('DEADBEEF', radix: 16);
  try {
    int.parse('not a number');
  } on FormatException catch (e) {
    print('Caught: ${e.message}');
  }
  var safe = int.tryParse('oops'); // null instead of an exception.
  print('$one $onePointOne $hex $safe');
}

The radix parameter is how you parse hexadecimal, binary or any base up to 36 — the reverse direction is toString(radix). For floats coming from JSON or a config file, double.tryParse() with a fallback default is the pattern you will use most.

Formatting numbers back to strings

The reverse direction has its own toolkit. toStringAsFixed(n) produces a decimal string with exactly n fraction digits, toStringAsExponential(n) uses scientific notation, and toStringAsPrecision(n) keeps n significant digits. Plain toString() gives the shortest string that round-trips the value.

void main() {
  var pi = 3.14159;
  print(pi.toStringAsFixed(2));       // 3.14
  print(pi.toStringAsExponential(2)); // 3.14e0
  print(pi.toStringAsPrecision(4));   // 3.142
  print(1400000.0.toStringAsExponential(2)); // 1.4e6
}

These return String values ready for display — and combining them with other text is exactly what string interpolation does best, as covered in dart-string-interpolation-raw-strings.md.

The conversion methods, and the truncation trap

num offers toInt(), toDouble() and the ...ToDouble() variants, plus round(), floor(), ceil() and truncate(). The trap is that toInt() — like truncate() — discards the fractional part rather than rounding it, and it does so toward zero in both directions.

void main() {
  print(2.7.toInt());    // 2 — truncates; round() would give 3.
  print(2.7.round());    // 3
  print(2.7.ceil());     // 3
  print(2.7.floor());    // 2
  print((-2.7).toInt()); // -2 — toward zero, not the nearest.
  print((-2.7).round()); // -3 — nearest integer.
  var seven = 7;
  print(seven.toDouble()); // 7.0 — widening is always safe.
}

If you mean “nearest,” call round(). If you mean “keep whole units of something,” toInt() on a positive value is fine — but never let a negative double reach toInt() expecting the nearest integer. For money or other exact quantities, convert to int minor units once and stay there; binary floating point cannot represent most decimals exactly, a point hammered home in dart-core-types-int-double-bool-string.md.

Hex, exponents and const arithmetic

Literals themselves support the same range of forms, and any arithmetic built purely from constant number literals is itself a compile-time constant — which is what makes const declarations with computed values possible, as shown in dart-final-vs-const.md.

void main() {
  var hex = 0xDEADBEEF; // 3735928559
  var exponent = 1.42e5; // 142000.0
  const msPerSecond = 1000;
  const secondsUntilRetry = 5;
  const msUntilRetry = secondsUntilRetry * msPerSecond;
  print('$hex $exponent $msUntilRetry ms');
}

Number literals are compile-time constants, and many arithmetic expressions are too, as long as every operand is a constant that evaluates to a number. That is the whole mechanism behind msUntilRetry — no runtime work, a value baked in before the program starts.

Conversion options compared

OperationResultWatch out for
a / bdoubleNever integer division, even for 7 / 1
a ~/ bintTruncates toward zero, unlike floor()
a % bnumEuclidean modulo: non-negative for a positive divisor
x.toInt() / x.truncate()intDiscards the fraction — it does not round
x.round() / floor() / ceil()intThe direction-aware choices
x.toDouble()doubleSafe widening for any value
int.parse(s) / double.parse(s)int / doubleThrows FormatException on bad input
int.tryParse(s)int?Returns null instead of throwing
toStringAsFixed(n) etc.StringFormatting only — no value change

Takeaways

num is the sealed umbrella over int and double, carrying every operation both types share while / always returns a double and ~/ always returns an int. Literals promote into a double context automatically, but real values never move between the two implicitly — you choose toDouble(), round(), toInt() or a parse, and you live with that choice’s rounding behavior. Format with toStringAsFixed and friends, parse with tryParse when input is untrusted, and reach for int minor units whenever exactness matters.

Takeaway: Use round() when you mean nearest, toInt() only when you mean truncate, and let num carry shared arithmetic while int and double keep their distinct contracts.

References