Dart Arithmetic Operators
Dart Arithmetic Operators
Arithmetic operators are used to do common math with numbers.
| Operator | Name | Description | Example |
|---|---|---|---|
+ | Addition | Adds two values | x + y |
- | Subtraction | Subtracts one value from another | x - y |
* | Multiplication | Multiplies two values | x * y |
/ | Division | Divides one value by another, the result is a double | x / y |
~/ | Integer division | Divides and removes the decimals, the result is an int | x ~/ y |
% | Modulus | Gives the remainder of a division | x % y |
- | Negation | Changes the sign of a value | -x |
++ | Increment | Adds 1 to a variable | x++ |
-- | Decrement | Subtracts 1 from a variable | x-- |
Example
void main() {
int x = 10;
int y = 3;
print(x + y);
print(x - y);
print(x * y);
print(-x);
}
Try it Yourself »
Result:
13
7
30
-10
Division
The / operator always gives a double, even when both numbers are integers:
Result:
5.0
2.5
The ~/ operator divides and removes the decimals.
The result is an int:
Example
void main() {
int cookies = 17;
int children = 5;
print(cookies ~/ children);
}
Try it Yourself »
Result:
3
Each child gets 3 cookies.
Modulus
The % operator gives the remainder, which is what is left over after a division:
Example
void main() {
int cookies = 17;
int children = 5;
print(cookies % children);
}
Try it Yourself »
Result:
2
2 cookies are left over.
The modulus is often used to check if a number is even or odd.
An even number has a remainder of 0 when you divide it by 2:
Result:
0
1
Mixing int and double
If one of the operands is a double, the result is also a double:
Example
void main() {
int items = 3;
double price = 2.5;
print(items * price);
print(items + 1.0);
}
Try it Yourself »
Result:
7.5
4.0
Increment and Decrement
The ++ operator adds 1 to a variable, and the -- operator subtracts 1:
Example
void main() {
int likes = 10;
likes++;
print(likes);
likes--;
likes--;
print(likes);
}
Try it Yourself »
Result:
11
9
You can write ++ before or after the variable.
The difference matters when you use the result in the same expression:
x++gives the old value, then adds 1++xadds 1, then gives the new value
Example
void main() {
int x = 5;
print(x++);
print(x);
int y = 5;
print(++y);
print(y);
}
Try it Yourself »
Result:
5
6
6
6