Summary: in this tutorial, you’ll learn about the Dart double type that represents double-precision floating-point numbers.
Introduction to Dart double type
Dart uses double
type to represent double-precision floating-point numbers. For example, the following declares a variable with the double
type:
void main() {
double price = 9.99;
print(price);
}
Code language: Dart (dart)
Output:
9.99
Code language: Dart (dart)
Comparing doubles
Since computers can only represent floating-point numbers approximately, comparing them may lead to an expected result. Consider the following example:
void main() {
double x = 0.3;
double y = 0.1 + 0.1 + 0.1;
bool isEqual = x == y;
print("$x == $y -> $isEqual ");
}
Code language: Dart (dart)
In this example, you may expect x
to be equal to y
but the result is different:
0.3 == 0.30000000000000004 -> false
Code language: Dart (dart)
The reason is that the 0.1 + 0.1 + 0.1
is not 0.3
but 0.30000000000000004
. This is because internally Dart only can represent the number 0.1 approximately.
It’s important to note that this problem is not Dart’s specific. It illustrates how the computers represent floating-point numbers internally.
Converting a string into a double
To convert a string to a double, you use the double.parse()
method. For example:
void main() {
String priceStr = "1.55";
double price = double.parse(priceStr);
print(price);
}
Code language: Dart (dart)
In this example, we convert the string "1.55"
to a double. The double.parse()
will throw an exception if the string cannot be converted into a double:
void main() {
String priceStr = "1.55x";
double price = double.parse(priceStr);
print(price);
}
Code language: Dart (dart)
Error:
Unhandled exception:
FormatException: Invalid double
1.55x
Code language: Dart (dart)
In this example, the double.parse()
couldn’t convert the string “1.55x” to a double. Therefore, it raised an exception.
Convert an integer into a double
To convert an integer into a double, you use the int.toDouble()
like the following example:
void main() {
int qty = 10;
double totalQty = qty.toDouble();
print(totalQty);
}
Code language: Dart (dart)
How it works.
First, declare the qty
variable as an integer and initialize its value to 10.
int qty = 10;
Code language: Dart (dart)
Second, convert the qty
into a double and assign its value to totalQty
variable:
double totalQty = qty.toDouble();
Code language: Dart (dart)
Third, display the totalQty
variable:
print(totalQty);
Code language: Dart (dart)
Summary
- Use
double
type to represent double-precision floating-point numbers. - Use
double.parse()
to convert a string into a double. - Use
int.toDouble()
to convert an integer into a double.