C++ Type Conversion
Type Conversion
Sometimes you need to change a value from one data type to another, like a decimal number to a whole number. This is called type conversion.
There are two kinds:
- Automatic conversion - C++ does it for you
- Manual conversion - you tell C++ to do it
Automatic Conversion
When you store a value of one type in a variable of another type, C++ converts it automatically.
An int can be stored in a double without any problem:
Example
int myInt = 9;
double myDouble = myInt; // int to double
cout << myDouble;
Note: myDouble now holds the value 9.0, but cout does not print zeros at the end of a decimal number. That is why it shows 9, not 9.0. See Decimal Precision to learn how to choose the number of decimals.
But when you store a double in an int, the decimals are lost:
Example
double price = 9.99;
int wholePrice = price; // double to int
cout << wholePrice;
Note: The decimals are cut off, not rounded. 9.99 becomes 9, not 10.
Manual Conversion
You can also convert a value yourself. In C++, the recommended way is static_cast. Write the new type inside < >, and the value inside the parentheses:
Example
double myDouble = 9.78;
int myInt = static_cast<int>(myDouble);
cout << myDouble << "\n";
cout << myInt;
You may also see the older C-style way in other code, where you write the new type in parentheses in front of the value:
Example
double myDouble = 9.78;
int myInt = (int) myDouble;
cout << myInt;
It does the same thing, but static_cast is easier to spot and safer to use.
Why Is Conversion Important?
When you divide two int values, the result is also an int, and the decimals are lost. This often gives the wrong answer, for example when you calculate an average:
Example
int sum = 7;
int count = 2;
double wrong = sum / count;
double right = static_cast<double>(sum) / count;
cout << wrong << "\n";
cout << right;
7 / 2 is calculated with whole numbers first, so the result is 3, even though it is stored in a double. Converting one of the values to double before dividing gives the correct answer, 3.5.
Real-Life Example
Here is a real-life example of type conversion. A game gives the player a score out of 500. The program shows the score as a percentage, and as stars (one star for every 20 percent):
Example
int maxScore = 500;
int userScore = 423;
// Convert to double, so the division keeps the decimals
double percentage = static_cast<double>(userScore) / maxScore * 100;
// Convert to int, to get whole stars (one star for every 20 percent)
int stars = static_cast<int>(percentage / 20);
cout << "Score: " << percentage << "%\n";
cout << "Stars: " << stars;
userScore is converted to double before dividing, so the decimals are kept (84.6). Then percentage / 20 (4.23) is converted to int, which cuts off the decimals and gives 4 stars.