Presentation is loading. Please wait.

Presentation is loading. Please wait.

Data Types Parsing Data

Similar presentations


Presentation on theme: "Data Types Parsing Data"— Presentation transcript:

1 Data Types Parsing Data
JavaScript Data Types Parsing Data

2 Learning Objectives By the end of this lecture, you should be able to:
Explain what is meant by the term "argument". Identify the three "data types" that we will discuss through the remainder of the course. Recognize how and when to apply the parseInt() and parseFloat() functions. Recognizing when not to use the parse functions.

3 "Arguments" In programming, it is important term to be familiar with the term "argument". An argument is the information you provide to a function when you invoke it. Some functions require 0 arguments, others may require 1 argument, and others can require multiple arguments. This is a very simple term, but it is important that you are comfortable using it. For example: alert('Hi'); --> the string 'hi' is the argument Math.sqrt(23.7); --> 23.7 is the argument Math.pow(3,4); --> this function has two arguments: 3 and 4 Date(); --> this function has 0 arguments

4 Brief review: The + operator
For each of the examples below, determine what value will result after applying the '+' operator. "Scooby" + "Doo"  "ScoobyDoo“ (two strings, therefore, concatenation) "5" + "6"  "56“ (also two strings, therefore, concatenation) 5 + 6  11 (two numbers, therefore addition) What about the following? "5" + 6  "56" 6 + "foo"  "6foo“ Recall that the moment you 'add' a string to anything -- including numbers -- the resulting value will be a string.

5 Data Types In many programming languages, every piece of data that you work has a “data type”. There are many different data types out there, but in this course, we will focus on three. The three data types you should be able to name: Strings  you are already familiar with these! Integers  numbers that are ‘whole’ (i.e. without a decimal) Floats  numbers that have a decimal Examples: x = 25  x is holding a String x = 25  x is holding an Integer x = 25.0  x is holding a Float

6 Examples In each of the four assignment statements below, identify the value and data type that will be stored inside the variable number: var x1 = "25"; var x2 = 10; var x3 = 5.3; var number; number = x1 + x2;  Value: "2510" Data type: string number = x1 + x3;  Value: "255.3" Data type: string number = x2 + x3;  Value: Data type: float number = x2 + 4;  Value: 14 Data type: int In the first two cases, we have a string on one side of the ‘+’ operator. Recall that the moment a string is present on either side, we will get concatenation. The third and fourth examples involve two numbers. In these case, then, the ‘+’ operator will do addition.

7 Fascinating… um, who cares?
All of this turns out to be hugely relevant in programming. The key point for our purposes is what happens when we retrieve information from a form. Key Point: Recall that all information retrieved from a form comes back as a string. Can you predict the output resulting from the following code? var age = document.getElementById('txtAge').value; //let's say the user entered 35 var nextYear; nextYear = age+1; alert("Next year you will be " + nextYear + " years old."); Answer: The formula ‘age+1’ will evaluate to 351! The reason is that the variable ‘age’ that was returned from the form is retrieved as a string. So, when we wrote: nextYear = age+1; we were adding a string to the number 1. As a result we ended up with concatenation. You can definitely expect exam question(s) relating to this!

8 How do we fix this? Let's return to the same example and see what we need to do to make things work the way we want them to. var age = document.getElementById('txtAge').value; //let's say the user entered 35 var nextYear; nextYear = age+1; //nextYear is holding the STRING "35" alert("Next year you will be " + nextYear + " years old."); Hopefully it is clear that in this particular situation, we want the '+' operator to do addition -- not concatenation. As you hopefully now realize, the variable age is holding the string "35". And, as we have now reiterated a few times, remember that the reason the variable is holding a string, is that all values that we retrieve from forms come back to the script as strings. What we need, then, is a way to convert the string "35" to the integer 35….

9 The parseInt() function
JavaScript includes a very useful function that specializes in converting strings into integers. This function is called parseInt(). parseInt() accepts a piece of information (typically a string) inside its parentheses. It then attempts to convert that information into an integer. If the information inside the parentheses “looks” like an number, then great! If the information inside the parentheses does not look like a string, however, your script will generate an error and your page will not display properly.

10 parseInt Examples Can you predict what will be stored inside the variable ‘temp’ in each of the following examples? var temp; temp = parseInt("352"); temp = parseInt(49.99); temp = parseInt("ten"); Line 2: temp will be assigned the integer 352 Easy conversion from string to int Line 3: temp will be assigned the integer 49 Easy conversion from float to int Important: Note that parseInt() does not round numbers up or down. Rather, the function simply chops off the decimal. We have a fancy word for this too (sorry): “truncation”. Line 4: Error: As humans, we can easily figure out what is supposed to happen. Sadly, computers are unable to make that leap (at least, without using artificial intelligence). The key point is that the value being converted must "resemble" a number in order for parseInt() to be able to figure out the conversion.

11 Solving our earlier problem using parseInt()
txtAge var age = document.getElementById('txtAge').value; //age is holding "35" age = parseInt(age); var nextYear = age+1; alert("Next year you will be " + nextYear); How does it work? We retrieve the value entered into the form, and store it in the variable 'age'. Note that age is holding a string (because all information that comes back from a form comes as a string). The the parseInt() function will look at the string “35” and do its very best to convert that string to an integer. In this case, it will have no problem doing so. We then take our integer 35 that was generated by the parseInt() function, and assign it to the variable age. So whereas age was previously holding the string “35”, it is now holding the integer 35. Because age is holding an integer, the formula ‘age+1’ now has an integer on both sides of the ‘+’ operator. Therefore, the '+' operator will do addition.

12 age = parseInt(age) ??? var age = document.getElementById('txtAge').value; //let's say the user entered 35 // this means that age is holding the string "35" age = parseInt(age); // parseInt("35") will produce the integer 35. // We then assign that 35 to the variable 'age' // So 'age' is now holding the integer 35 var nextYear = age+1; alert("Next year you will be " + nextYear); "35" age 35 age Important: Note that when you assign a value to a variable, any previous value that was stored inside will be deleted and replaced by the new value. In this example, the previous value of "35" will be replaced by the new value: 35. 36 nextYear

13 How the parseInt()function works
Every built-in function comes with a little "instruction book" that programmers typically refer to as the "documentation" or "docs". Programmers who encounter a useful function typically spend some time checking out the documentation to get an idea of how the function works and any potential pitfalls or 'gotchas' that they might need to know about. Here are a few points taken from the parseInt() documentation: The function will examine the "argument" (the information inside the parentheses). If the argument does NOT begin with a digit or a minus sign, the function will return an error. If the argument begins with a digit or a minus sign, the function will examine that value until it encounters any non-digit character. The function will then return all the numeric characters it encountered as an integer. As is very often the case, one of the best ways to see how a function works is to look at some examples: parseInt("359")  returns the integer 359 parseInt("(352)");  returns an error – does not start with a – or digit parseInt("35.9");  returns the integer 35 parseInt("-35.9");  returns the integer -35 parseInt(" ");  returns the integer 35 parseInt("I am 35 years old.");  Error – does not begin with a digit or –

14 Summary - Key Points Whenever you read in a value from a form and wish that value to be treated as an integer number, you should invoke the parseInt()function. Example: var birthYear = document.getElementById('txtYearBorn').value; //Clearly we wish 'birthYear' to hold an integer //Therefore, we must do the following: birthYear = parseInt(birthYear); //birthYear can now be treated as a regular number From this point forward, i.e. throughout the remainder of the course: Whenever you read in a value from a web form that you know is intended to be an integer quantity, you must invoke the parseInt() function on that number. However, if you are NOT reading in a quantity, (e.g. you are retrieving, say, a telephone number), you should never invoke the parseInt() function. The grader will deduct points every time you forget to do so!  txtYearBorn

15 parseFloat() What if the number you are planning to retrieve may contain decimals? E.g. The time to complete a 100 meter dash, The cost of a gallon of gas, etc Recall that parseInt() stops parsing the moment it encounters a decimal. (It doesn’t even round up or down!) Therefore, if you want to keep your decimals, you would not want to use parseInt(). Instead, you must use parseFloat() For example, suppose you are recording the race time for a 100 meter sprint where the times are often recorded to hundredths of a second. In this case, we would absolutely need to keep the decimal places. Therefore, we must use parseFloat() instead of parseInt() var raceTime = document.getElementById('txtRaceTime').value; raceTime = parseFloat(raceTime); txtRaceTime

16 Should I use parseInt() or parseFloat() ?
What if you are not sure if the value will have decimals or not? In this case, the best bet will be to err on the side of caution and use parseFloat(). That way, if the user does enter a value with decimals, you won’t lose thosedecimal values. If the user ends up entering an integer value, all that will happen is that you will see a '.0' appended to the end of the value. For example, if the user enters exactly 14 for, say, a race time, then parseFloat() will convert it to 14.0. If you're not sure, use parseFloat()

17 When NOT to use parseInt() and parseFloat()
From this point forward, you must always use parseInt() or parseFloat() But ONLY when retrieving information that involves a quantity! Examples: age, weight, cost of an item, time to run a race, number of days to ship a package, etc, etc, etc If you are not reading in a quantity (e.g. a telephone-number, zip code, etc), do not use a parse function! In the same way that you will be penalized for failing to use these functions when appropriate, you will also be penalized if you use them in inappropriate situations. One good rule of thumb is to ask yourself if there is any conceivable situation in which you might want to do a mathematical calculation with the number. e.g. If you are asking someone their birth year, you might want to subtract it from the current year in order to determine how old they are. So you would want to parse it. As long as you review and understand the underlying concept, and you should have no problem at all, figuring out when to and when not-to use these functions.

18 Examples Which of the following should be parsed? Should we use parseInt or parseFloat? Or neither? The user’s age The user’s phone number The user’s birth year The user’s weight The user’s zip code Answers: parseFloat() most likely. While most users will enter a whole number, you never know if someone might enter a decimal. If you think there is even a possibility that the user would enter an age with a decimal, then you should use parseFloat(). Neither. Do not use any parse function. Even if the user enters the number without any parentheses, or dashes, etc, it is still a string. It is hard to envision a situation where you would ever do math on it! parseInt(). You might want to subtract from the current year in order to determine their age. Probably parseFloat(). There are definitely people who know their weight to the nearest 10th of a pound! Because this is a real possibility, I’d use parseFloat() here. It won’t hurt anything if they do enter a whole number. Do not use a parse function here. Other than sorting (which you can do with strings), there is no “math” I can envision being done on a zip code!

19 File: parse_example.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Parse Example</title> <script> function calcNextYear() { var ageThisYear, ageNextYear; ageThisYear = document.getElementById('txtAge').value; ageThisYear = parseInt(ageThisYear); ageNextYear = ageThisYear + 1; alert("Next year, you will be: " + ageNextYear + " years old!"); } </script> </head> <body> <h1>Parse Example</h1> <p>How old are you now? <input type="text" id="txtAge"> <p><input type="button" value="How old will I be next year?" onclick="calcNextYear()"> </body> </html>

20 Be sure to invest the necessary time being able to apply as well as understanding with the techniques we have just discussed. You will encounter parseInt() and parseInt() constantly over the remainder of the course as well as in your exams.

21 File: fahrenheit_celcius_converter.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Temperature Converter</title> <script> function convertToCelcius() { var fahrenheit, celcius; fahrenheit = document.getElementById('txtFahrenheit').value; fahrenheit = parseFloat(fahrenheit); //people may well enter a decimal here, so use parseFloat celcius = (fahrenheit-32)*5.0/9; //Should we parse 'celcius' ?? //No! celcius is holding a number -- NOT a string //therefore we do not need to parse it. alert(fahrenheit + " degrees F corresponds to " + celcius + " degrees C."); } </script> </head> <body> <h2>Temperature Converter</h2> <form id="conversionForm"> <p>Enter a temperature in fahrenheit: <input type="text" id="txtFahrenheit"> <button onclick="convertToCelcius()">Convert</button> </form> </body> </html>

22 File: bmi_calculator.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>BMI Calculator</title> <script> function calculateBMI() { var height, weight, bmi; height = document.getElementById('txtHeight').value; weight = document.getElementById('txtWeight').value; height = parseFloat(height); weight = parseFloat(weight); bmi = weight*703 / (height*height); alert("For a weight of " + weight + " pounds, " + "and a height of " + height + " inches, " + "your BMI is " + bmi + "."); } </script> </head> <body> <h2>BMI Calculator</h2> <form id="bmiInfo"> <p>Enter your height in inches: <input type="text" id="txtHeight" size="10"> <p>Enter your weight in pounds: <input type="text" id="txtWeight" size="8" > <p><button onclick="calculateBMI()">Tell me my BMI</button> </form> </body> </html> We do not parse bmi since it is already holding a number.

23 KEEP THIS??? <!DOCTYPE html> <html lang="en"> <head>
<meta charset="utf-8"> <title>Conversions with innerHTML</title> </head> <body> <p>Enter an amount in pounds: <input type="text" id="txtPounds"> <input type="button" value="Convert to kilograms" onclick="convertKilos()"> <div id="conversionResults"> </div> <script> function convertKilos() { var pounds = document.getElementById("txtPounds").value; pounds = parseFloat(pounds); var kilos = pounds*2.28; var output = pounds + " pounds equals " + kilos + " kilograms."; document.getElementById("conversionResults").innerHTML = output; } </script> </body> </html> KEEP THIS???

24 Another example FILE: innerHTML_conversions.html KEEP THIS???

25 Just FYI, there is a JavaScript function called Number() (yes, the 'N' is capitalized), that works very similarly to the parse functions we have been discussing. There are good reasons both for and against using Number() instead of the parse functions. The parse functions require a bit more effort to understand and work with up front, but they are very useful for us to explore datatypes. And understanding datatypes is super-important in programming. Once you understand the parse functions, should you choose or work with a team that uses Number() down the road, you will have very little difficulty learning how to use that function. FYI: Number()


Download ppt "Data Types Parsing Data"

Similar presentations


Ads by Google