Download presentation
Presentation is loading. Please wait.
1
Data Type Conversion ICS2O
2
Learning Goals Students will:
Learn how to convert between two different number types in a mathematical expression. Learn how to convert between text and numerical values.
3
Type Casting Used when converting between different number types.
Ex. Performing a calculation involving integers and storing the final result in a variable of type double int length = 2; double width = 3.7; int area; area = length * (int)width; System.out.println(“The area of the rectangle is “ + area); Type casting is necessary in the calculation for the area since the variable area has been declared as an int, while width is declared as type double. The (int) is used to cast the double number as an int number.
4
Truncation When you cast a double to an integer, the value is rounded down to the nearest integer. This is called truncation. Ex. Casting a variable with a value of 3.78 results in a value of 3. This can lead to unexpected results since the value is not rounded according to mathematical rules. You can avoid truncation by adding 0.5 or subtracting 0.5 (for negative numbers) to the variable of type double before type casting. Ex. The calculation for area can be adjusted to round using the following code. area = length * (int)(width + 0.5);
5
Division Casting becomes very useful when you are doing decimal division of integer values. Dividing two integers will always truncate the value so that the decimal is not preserved. If you cast your int numbers to double numbers, then you are able to preserve the decimal portion. int pizzaSlices = 5; int peopleEating = 2; double slicesPerPerson; slicesPerPerson = pizzaSlices / peopleEating; //integer division; result = 2 slicesPerPerson = (double)pizzaSlices / (double)peopleEating; //decimal division; result = 2.5
6
Converting from Text to Numeric Data
You may also need to convert from text to numeric data. To do this, we use a parse command. String gradeMath = “85”; String gradeScience = “75”; float average; average = (Float.parseFloat(gradeMath) + Float.parseFloat(gradeScience)) / 2; System.out.println("Your average for math and science is " + average); In this example, the grades are stored as strings but are used in a calculation to find the average. The type you wish to convert to has an attribute for this purpose. Float.parseFloat(<string>) Double.parseDouble(<string>) Integer.parseInt(<string>)
7
Convert from Numeric to String
A similar command can be used to convert a numerical value to a string. Float.toString(<number>) Double.toString(<number>) Integer.toString(<number>) Ex. Converting the average value from the previous example. System.out.println("Your average for math and science is " + Float.toString(average));
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.