Skip to main content

Command Palette

Search for a command to run...

Dart Number & Dart Int & Dart Double

Published
2 min read
Dart Number & Dart Int & Dart Double
P

I'm Computer Engineering Student. Learning Status DSA in Java, Dart Development, Python in Django Development. Best part is Communication Skills, Marketing, Accounting.

In Dart, numbers are fundamental for various calculations and data representation. Here's a comprehensive explanation of int, double, and the general num type:

1. int:

  • Represents whole (integer) numbers without decimal points.

  • Declaration:

Dart

int age = 30;
  • Range:

    • The range depends on the platform:

      • Native platforms (mobile/desktop): Typically, -2⁶³ to 2⁶³ - 1.

      • Web platform: Limited to JavaScript's number representation (double-precision floating-point with no fractional part). This effectively restricts the range to -2⁵³ to 2⁵³ - 1.

2. double:

  • Represents numbers with decimal points.

  • Declaration:

Dart

double pi = 3.14159;
  • Storage: Uses 64-bit double-precision floating-point format according to the IEEE 754 standard.

  • Precision: Due to the nature of floating-point representation, calculations might involve minor rounding errors.

3. num:

  • The base type for both int and double.

  • Represents all numeric values.

  • Usage:

    • Useful when you need a variable to hold either an integer or a double value:

Dart

    num distance = 10.5; // Can be assigned both int and double values

Key points:

  • Type inference: Dart often infers the number type automatically based on the assigned value.

  • Conversion:

    • Explicit conversion using toInt() or toDouble() methods:

Dart

    int ageInYears = pi.toInt(); // Truncates decimal part
    double exactAge = ageInYears.toDouble();

Choosing the right type:

  • Use int when dealing with whole numbers (e.g., counting, indexing).

  • Use double when representing values with decimal precision (e.g., scientific calculations, measurements).

  • Use num when the variable might hold either type during the program's execution.

Additional considerations:

  • For calculations requiring high precision, explore libraries like dart:math for alternative representations like BigInt.

Resources:

By understanding these data types and their appropriate usage, you can effectively represent numeric data in your Dart applications.

More from this blog

Parth Chauhan's blog

87 posts

Learner, Accountant, Marketer, Programmer.

Dart Number & Dart Int & Dart Double