Numbers are fundamental to programming. Dart provides two main numeric types: int for whole numbers and double for decimal numbers. Understanding how to work with numbers effectively is essential for calculations, data processing, and building real-world applications.
Integer Type (int)
The int type represents whole numbers without decimal points. In Dart, integers can be as large as the platform allows - on native platforms, they can be 64-bit values ranging from -2⁶³ to 2⁶³-1.
Working with Integers
1// Integer declarations2int age = 25;3int score = 100;4int temperature = -5;5 6// Large integers7int bigNumber = 9223372036854775807; // Maximum 64-bit int8 9// Integer arithmetic10int a = 10;11int b = 3;12 13print(a + b); // 13 - Addition14print(a - b); // 7 - Subtraction15print(a * b); // 30 - Multiplication16print(a ~/ b); // 3 - Integer division (truncates)17print(a % b); // 1 - Modulo (remainder)18 19// Integer division vs regular division20print(10 / 3); // 3.3333... (returns double)21print(10 ~/ 3); // 3 (returns int, truncates decimal)HintIntegers are perfect for counting, indexing, and situations where decimal precision is not needed. Use ~/ for integer division to get a whole number result.
Double Type (double)
The double type represents 64-bit floating-point numbers (decimals). Use double when you need precision for calculations involving fractions, percentages, or measurements.
Working with Doubles
1// Double declarations2double price = 19.99;3double temperature = 36.6;4double pi = 3.14159;5 6// Scientific notation7double speedOfLight = 3.0e8; // 3.0 × 10⁸ = 300,000,0008double tiny = 1.5e-5; // 1.5 × 10⁻⁵ = 0.0000159 10// Double arithmetic11double x = 10.5;12double y = 3.2;13 14print(x + y); // 13.7 - Addition15print(x - y); // 7.3 - Subtraction16print(x * y); // 33.6 - Multiplication17print(x / y); // 3.28125 - Division18 19// Precision considerations20double result = 0.1 + 0.2;21print(result); // 0.30000000000000004 (floating-point precision issue)22print(result.toStringAsFixed(1)); // "0.3" (formatted)HintDoubles are essential for precise calculations. Be aware of floating-point precision limitations when comparing decimal values.
The num Type
The num type is the parent type of both int and double. Use num when a variable could be either an integer or a double.
Using num
1// num can hold both int and double2num count = 10; // int3num price = 19.99; // double4 5// Useful for functions that accept both types6num add(num a, num b) {7 return a + b;8}9 10print(add(5, 3)); // 8 (int + int)11print(add(5.5, 3.2)); // 8.7 (double + double)12print(add(5, 3.2)); // 8.2 (int + double = double)13 14// Type checking15num value = 42;16print(value is int); // true17print(value is double); // false18print(value is num); // true19 20value = 42.0;21print(value is int); // false22print(value is double); // trueHintUse num for flexibility when you need to work with both integers and doubles. The result type depends on the operands.
Number Conversion and Parsing
Converting between number types and parsing strings to numbers are common operations in Dart applications.
Converting and Parsing Numbers
1// Converting int to double2int wholeNumber = 42;3double decimal = wholeNumber.toDouble(); // 42.04 5// Converting double to int (truncates decimal part)6double price = 19.99;7int rounded = price.toInt(); // 19 (truncates)8int roundedUp = price.ceil(); // 20 (rounds up)9int roundedDown = price.floor(); // 19 (rounds down)10int roundedNearest = price.round(); // 20 (rounds to nearest)11 12// Parsing strings to numbers13String ageText = '25';14int age = int.parse(ageText); // 2515 16String priceText = '19.99';17double productPrice = double.parse(priceText); // 19.9918 19// Safe parsing with tryParse (returns null if invalid)20String invalid = 'abc';21int? result = int.tryParse(invalid); // null (doesn't throw error)22 23String valid = '100';24int? number = int.tryParse(valid); // 10025 26// Converting numbers to strings27int count = 42;28String countText = count.toString(); // "42"29 30double pi = 3.14159;31String piText = pi.toString(); // "3.14159"32String piFixed = pi.toStringAsFixed(2); // "3.14"33String piPrecision = pi.toStringAsPrecision(3); // "3.14"HintAlways use tryParse() when parsing user input to handle invalid data gracefully. Use toStringAsFixed() for consistent decimal formatting.
Common Number Operations
Dart provides many useful methods and operators for working with numbers.
Number Methods and Operations
1// Absolute value2int negative = -42;3print(negative.abs()); // 424 5// Power and square root (requires dart:math)6import 'dart:math';7 8print(pow(2, 3)); // 8.0 (2³)9print(sqrt(16)); // 4.0 (√16)10 11// Min and Max12print(min(10, 5)); // 513print(max(10, 5)); // 1014 15// Rounding operations16double value = 3.7;17print(value.round()); // 418print(value.floor()); // 319print(value.ceil()); // 420print(value.truncate()); // 321 22// Check if finite or infinite23double finite = 42.0;24double infinite = double.infinity;25double notANumber = double.nan;26 27print(finite.isFinite); // true28print(infinite.isInfinite); // true29print(notANumber.isNaN); // true30 31// Clamping values (keeping within range)32int score = 150;33int clamped = score.clamp(0, 100); // 100 (limited to max 100)34 35double temperature = -5.0;36double safe = temperature.clamp(0.0, 40.0); // 0.0 (limited to min 0)HintThese methods help you perform common mathematical operations and validations on numbers.
Working with dart:math
The dart:math library provides advanced mathematical functions and constants.
Using dart:math Library
1import 'dart:math';2 3// Mathematical constants4print(pi); // 3.1415926535897935print(e); // 2.7182818284590456 7// Trigonometric functions (angles in radians)8print(sin(pi / 2)); // 1.09print(cos(0)); // 1.010print(tan(pi / 4)); // 1.011 12// Exponential and logarithmic13print(exp(1)); // 2.718... (e¹)14print(log(e)); // 1.0 (natural log)15 16// Random numbers17Random random = Random();18int randomInt = random.nextInt(100); // 0 to 9919double randomDouble = random.nextDouble(); // 0.0 to 1.020bool randomBool = random.nextBool(); // true or false21 22// Random in range23int diceRoll = random.nextInt(6) + 1; // 1 to 624double percentage = random.nextDouble() * 100; // 0.0 to 100.025 26// Seeded random (reproducible)27Random seeded = Random(42);28print(seeded.nextInt(100)); // Always same sequence with same seedHintThe dart:math library is essential for advanced calculations, trigonometry, and generating random numbers.
Practical Examples
Real-world scenarios demonstrating number operations in Dart applications.
Real-World Number Usage
1import 'dart:math';2 3// Calculate discount price4double calculateDiscount(double price, int discountPercent) {5 double discount = price * (discountPercent / 100);6 double finalPrice = price - discount;7 return double.parse(finalPrice.toStringAsFixed(2)); // Round to 2 decimals8}9 10print(calculateDiscount(99.99, 20)); // 79.9911 12// Calculate BMI (Body Mass Index)13double calculateBMI(double weightKg, double heightM) {14 double bmi = weightKg / pow(heightM, 2);15 return double.parse(bmi.toStringAsFixed(1));16}17 18print(calculateBMI(70, 1.75)); // 22.919 20// Generate random PIN21String generatePIN(int length) {22 Random random = Random();23 String pin = '';24 for (int i = 0; i < length; i++) {25 pin += random.nextInt(10).toString();26 }27 return pin;28}29 30print(generatePIN(4)); // e.g., "7392"31 32// Calculate compound interest33double calculateCompoundInterest({34 required double principal,35 required double rate,36 required int years,37 int timesPerYear = 1,38}) {39 double amount = principal * pow(1 + (rate / timesPerYear), timesPerYear * years);40 return double.parse(amount.toStringAsFixed(2));41}42 43print(calculateCompoundInterest(44 principal: 1000,45 rate: 0.05, // 5%46 years: 10,47 timesPerYear: 12, // Monthly compounding48)); // 1647.01HintThese examples show how to use numbers in real applications: e-commerce calculations, health metrics, security, and financial computations.
Loot collected
Key takeaways- Use int for whole numbers and double for decimal numbers
- The num type can hold both int and double values
- Use ~/ for integer division and / for regular division
- Always use tryParse() when parsing user input to handle errors gracefully
- Be aware of floating-point precision issues when working with doubles
- Use toStringAsFixed() to format numbers with specific decimal places
- The dart:math library provides advanced mathematical functions and random number generation
- Use clamp() to keep values within a specific range
- Methods like round(), floor(), and ceil() help control decimal precision
Side quests
Practice exercises
Exercise 1: Temperature Converter
Write a function that converts Celsius to Fahrenheit. Formula: F = (C × 9/5) + 32
Reveal solutionHide solution
1double celsiusToFahrenheit(double celsius) {2 return (celsius * 9 / 5) + 32;3}4 5print(celsiusToFahrenheit(0)); // 32.06print(celsiusToFahrenheit(100)); // 212.0Exercise 2: Circle Calculator
Create a function that calculates the area of a circle given its radius. Formula: Area = π × r²
Reveal solutionHide solution
1import 'dart:math';2 3double calculateCircleArea(double radius) {4 return pi * pow(radius, 2);5}6 7print(calculateCircleArea(5).toStringAsFixed(2)); // "78.54"Exercise 3: Safe Division
Write a function that safely divides two numbers and returns null if division by zero is attempted.
Reveal solutionHide solution
1double? safeDivide(num a, num b) {2 if (b == 0) return null;3 return a / b;4}5 6print(safeDivide(10, 2)); // 5.07print(safeDivide(10, 0)); // nullExercise 4: Random Range
Create a function that generates a random integer between min and max (inclusive).
Reveal solutionHide solution
1import 'dart:math';2 3int randomInRange(int min, int max) {4 Random random = Random();5 return min + random.nextInt(max - min + 1);6}7 8print(randomInRange(1, 10)); // Random number between 1 and 10