Dive into Dart: int, double, num

Murtaza Sulaihi
6 min readJan 4, 2024

--

Numeric Flexibility in Dart: Harnessing the Power of ‘num’ for Varied Data Types. Delve into the versatility of the ‘num’ data type in Dart, navigating scenarios where flexibility in handling both integers and doubles is paramount.

Introduction:

Welcome to the world of Dart programming, where data types play a crucial role in handling numbers. As a beginner navigating the domain of Dart, it is essential to understand the nuances of data types for writing efficient and robust code. This article demystifies three fundamental Dart data types: ‘int’, ‘double’, and ‘num’.

Dart, a language developed by Google, is renowned for its versatility and simplicity. The ‘int’ data type is your go-to choice for handling whole numbers, allowing you to seamlessly represent quantities, counts, and indices in your code. On the other hand, ‘double’ steps onto the stage when precision matters, accommodating decimal points for a myriad of real-world applications.

In situations where you might encounter both integers and doubles, the ‘num’ data type comes to the rescue, offering a generic numeric type that flexibly adapts to the requirements of your program. This trio of data types lays the foundation for numeric representation in Dart, each serving a unique purpose in the programming landscape.

But it doesn’t stop there. This article introduces the basics of ‘int’, ‘double’, and ‘num’ and then uses real-world examples to showcase their practical applications. From calculating shopping cart totals and representing temperatures to handling generic numeric values, we’ll explore scenarios that illustrate when and how to employ these data types effectively.

Additionally, we delve into data type conversion — a skill every Dart programmer must master. Learn how to seamlessly transition between ‘int’, ‘double’, and ‘String’, ensuring your code remains flexible and adaptable to diverse input scenarios.

Whether you’re just starting your Dart programming journey or looking to enhance your understanding of numeric data types, this article aims to provide clarity and practical insights. Join us as we demystify Dart data types, empowering you to write functional and optimised code for performance.

Properties:

  • hashcode: This property is used to get the hash code of the given number.
  • isFinite: This property will return true if the given number is finite.
  • isInfinite: If the number is infinite, this property will return true.
  • isNan: If the number is non-negative, this property will return true.
  • isNegative: If the number is negative, this property will return true.
  • sign: This property is used to get -1, 0, or 1 depending upon the sign of the given number.
  • isEven: If the given number is even, this property will return true.
  • isOdd: If the given number is odd, this property will return true.

Methods:

  • abs(): This method gives the absolute value of the given number.
  • ceil(): This method gives the ceiling value of the given number.
  • floor(): This method gives the floor value of the given number.
  • compareTo(): This method compares the value with other numbers.
  • remainder(): This method gives the truncated remainder after dividing the two numbers.
  • round(): This method returns the round of the number.
  • toDouble(): This method gives the double equivalent representation of the number.
  • toInt(): This method returns the integer equivalent representation of the number.
  • toString(): This method returns the String equivalent representation of the number
  • truncate(): This method returns the integer after discarding fraction digits.

Let’s break down the concepts of ‘int’, ‘double’, and ‘num’ in Dart, along with their usage, differences, conversions, and optimisation tips. We’ll also explore examples for each data type.

1. int (Integer):

  • Usage: Used to represent whole numbers (integers) without any decimal points.
int myAge = 25;
  • Conversion to String:
int myAge = 25;
String ageString = myAge.toString();
  • Examples:
// Calculating the total cost of items in a shopping cart
int itemPrice = 50;
int quantity = 3;
int totalCost = itemPrice * quantity;

// Representing the number of pages in a book
int totalPages = 350;

// Counting the number of users in a system
int userCount = 100;

2. double (Double Precision Floating-Point):

  • Usage: Used to represent numbers with decimal points.
double temperature = 26.5;
  • Conversion to String:
double temperature = 26.5;
String tempString = temperature.toString();
  • Examples:
// Representing the average score in a game
double averageScore = 85.5;

// Storing the price of an item with fractional value
double itemPrice = 19.99;

// Calculating the area of a circle with a radius
double radius = 3.0;
double area = 3.14 * radius * radius;

3. num (Number):

  • Usage: A generic numeric type that can represent both integers and doubles.
num myNumber = 42;
  • Conversion to String:
num myNumber = 42;
String numString = myNumber.toString();
  • Examples:
// Calculating the total cost with a mix of integer and double values
num totalCost = 150.75;

// Representing the quantity of a product with a mix of integer and double values
num productQuantity = 5;

// Storing a generic numeric value in a variable
num genericValue = 123.456;

When to Use Each Data Type:

  • Use int when dealing with whole numbers.
  • Use double when dealing with numbers that have decimal points.
  • Use num when the variable might hold either an integer or a double.

Optimisation Tips:

  • Use the most specific type (int or double) to avoid unnecessary precision.
  • Be mindful of potential precision loss when converting between double and int.
  • Use num cautiously, as it can lead to less optimised code compared to specific types.

Conversion between Data Types:

  • From int/double to String:
int myInt = 42;
double myDouble = 3.14;

String intString = myInt.toString();
String doubleString = myDouble.toString();
  • From String to int/double:
String intString = "42";
String doubleString = "3.14";

int parsedInt = int.parse(intString);
double parsedDouble = double.parse(doubleString);

Remember to handle exceptions when parsing, as it might fail if the string is not a valid number.

I hope this explanation and examples help you understand the usage of ‘int’, ‘double’, and ‘num’ in Dart as a beginner.

Through this Flutter Counter App, we’ll understand the use of ‘int’ for item counts, ‘double’ for precise prices, and ‘num’ for flexible total costs. This application aids in exploring and comprehending numeric representations in Dart programming.

https://gist.github.com/timelessfusionapps/0ba2a3aaf3fb2d0d4209dd5764274b72


import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}

class MyHomePage extends StatefulWidget {
final String title;

const MyHomePage({
Key? key,
required this.title,
}) : super(key: key);

@override
State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
// Using 'int' to represent whole numbers (e.g., count of items)
int itemCount = 0;

// Using 'double' for precise calculations (e.g., item price)
double itemPrice = 5.99;

// Using 'num' for flexibility (e.g., total cost may include whole and fractional parts)
num totalCost = 0;

void _incrementCounter() {
// Increment the item count when the button is pressed
setState(() {
itemCount++;
// Calculate the total cost using 'num'
totalCost = itemCount * itemPrice;
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Counter App'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Item Count: $itemCount',
style: TextStyle(fontSize: 20),
),
SizedBox(height: 20),
Text(
'Total Cost: \$${totalCost.toStringAsFixed(2)}',
style: TextStyle(fontSize: 20),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
_incrementCounter();
},
child: Text('Add Item'),
),
],
),
),
);
}
}

In this example:

  • The itemCount variable uses the 'int' data type to represent the count of items.
  • The itemPrice variable uses the 'double' data type to represent the price of each item.
  • The totalCost variable uses the 'num' data type to represent the total cost, allowing flexibility for both integer and decimal parts.

The app displays the current item count and total cost, and a button allows you to increment the item count, updating the total cost accordingly.

Conclusion:

In conclusion, this journey into the Dart programming language has provided invaluable insights into the power and versatility of numeric data types. We’ve witnessed the role of ‘int’, ‘double’, and ‘num’ in shaping how we handle numbers, from representing whole quantities to accommodating decimal precision and offering flexibility for various scenarios.

Through real-world examples in our Counter App, we’ve grasped the fundamental concepts of these data types and gained practical experience in their application. The ability to seamlessly transition between these types and harness their unique strengths is a skill that will undoubtedly enhance your Dart programming proficiency.

As you continue your programming endeavours, remember that choosing the correct data type is not just a matter of syntax but a strategic decision that impacts the efficiency and precision of your code. The world of Dart awaits and armed with the knowledge gained here, you’re well-equipped to navigate and optimise your numeric representations. Happy coding!

--

--

Murtaza Sulaihi

By profession, I am a school professor and I also develop Android applications and also Flutter applications.