Dart Numbers
In Dart, numbers are a fundamental data type used to represent numerical values, including integers and floating-point numbers. Dart has a rich set of features for working with numbers, including built-in arithmetic operations, type conversion, and specialized numerical types. Below is an overview of how numbers are handled in Dart.
Number Types in Dart
Dart primarily has two types of numbers:
- Integers (
int
) - Floating-Point Numbers (
double
)
1. Integers (int
)
Description: An integer in Dart is a whole number, which can be positive, negative, or zero. Dart's
int
type can represent integers of arbitrary precision, meaning it can handle very large or very small numbers without overflow issues.Example:
2. Floating-Point Numbers (double
)
Description: A
double
in Dart is used to represent numbers with decimal points. It follows the IEEE 754 standard for double-precision floating-point arithmetic.Example:
Special Number Values
Dart also supports special number values:
NaN
(Not a Number): Represents a value that is not a valid number, typically resulting from undefined operations (e.g.,0/0
).Infinity
and-Infinity
: Represents positive and negative infinity, respectively. These can occur when dividing a positive number by zero or when calculations exceed the representable range.
Example:
Numeric Literals
Dart supports various ways to define numeric literals:
- Decimal Literals: Regular numbers, e.g.,
42
,3.14
. - Hexadecimal Literals: Represented with a prefix
0x
, e.g.,0x2A
for 42. - Binary Literals: Represented with a prefix
0b
, e.g.,0b101010
for 42. - Octal Literals: (Dart 2.0 and later do not support octal literals directly.)
Example:
Arithmetic Operations
Dart provides a rich set of arithmetic operators to perform operations on numbers:
- Addition (
+
) - Subtraction (
-
) - Multiplication (
*
) - Division (
/
): Returns adouble
. - Integer Division (
~/
): Returns anint
by discarding the fractional part. - Modulus (
%
): Returns the remainder of a division.
Example:
Type Conversion
Dart provides methods to convert between different numeric types, such as from double
to int
and vice versa.
From
double
toint
: UsetoInt()
method.From
int
todouble
: UsetoDouble()
method.
Example:
Conclusion
Numbers in Dart are versatile and can be used in various ways to represent both whole and fractional values. With support for different numeric types, special values, arithmetic operations, and type conversions, Dart provides a robust framework for numerical computations. Understanding how to work with numbers effectively is essential for writing efficient Dart programs, whether you are developing simple applications or complex algorithms.