Data Types Parsing Data

Slides:



Advertisements
Similar presentations
Events Part III The event object. Learning Objectives By the end of this lecture, you should be able to: – Learn to use the hover() function – Work with.
Advertisements

Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
Introduction to a Programming Environment
Escaping Characters document.write(). Learning Objectives By the end of this lecture, you should be able to: – Recognize some of the characters that can.
Working with Numbers parseInt() and parseFloat() Math.round() Other Math object functions isNaN() toFixed()
Input, Output, and Processing
5 BASIC CONCEPTS OF ANY PROGRAMMING LANGUAGE Let’s get started …
Mathematical Calculations in Java Mrs. G. Chapman.
Mathematical Calculations in Java Mrs. C. Furman.
CSD 340 (Blum)1 Starting JavaScript Homage to the Homage to the Square.
1 Chapter 3 – Examples The examples from chapter 3, combining the data types, variables, expressions, assignments, functions and methods with Windows controls.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Arithmetic, Functions and Input 9/16/13. Arithmetic Operators C++ has the same arithmetic operators as a calculator: * for multiplication: a * b – Not.
Introduction to Arrays. Learning Objectives By the end of this lecture, you should be able to: – Understand what an array is – Know how to create an array.
JavaScript Part 1 Introduction to scripting The ‘alert’ function.
JavaScript: Conditionals contd.
JavaScript Controlling the flow of your programs with ‘if’ statements
Precedence Operators Error Types
Mr Barton’s Maths Notes
Notes 1.2: Significant Figures
Moving away from alert() Using innerHTML Using an empty div section
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
Attend to Precision Introduction to Engineering Design
Topics Designing a Program Input, Processing, and Output
User-Written Functions
Regular Expressions 'RegEx'.
Chapter 6 JavaScript: Introduction to Scripting
Predefined Functions Using the JavaScript Documentation
Concatenation Comments
Formatting Output.
Chapter 2 - Introduction to C Programming
2.5 Another Java Application: Adding Integers
Mr F’s Maths Notes Number 7. Percentages.
Lecture 25 More Synchronized Data and Producer/Consumer Relationship
Variables, Expressions, and IO
Retrieving information from forms
Useful String Methods Cont…
JavaScript Part 2 Organizing JavaScript Code into Functions
Chapter 2 - Introduction to C Programming
Intro to PHP & Variables
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
Introduction to C++ Programming
CDA 3100 Summer 2013.
Arithmetic Expressions & Data Conversions
We are starting JavaScript. Here are a set of examples
Mr Barton’s Maths Notes
JavaScript Variables.
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Introducing JavaScript
This is an introduction to JavaScript using the examples found at the CIS17 website. In previous examples I specified language = Javascript, instead of.
Standard Normal Table Area Under the Curve
Working with Strings.
Arithmetic Expressions & Data Conversions
Events Part III The event object.
JavaScript Variables.
Random Stuff Colors Sizes CSS Shortcuts.
Working with Numbers parseInt() and parseFloat() Math.round()
Using the Rule Normal Quantile Plots
JavaScript Part 2 Organizing JavaScript Code into Functions
Retrieving information from forms
Data Types Parsing Data
Introduction to scripting
JavaScript Variables.
Adios alert() Using innerHTML Using an empty section
Concatenation of Strings JavaScript Comments
Using the Rule Normal Quantile Plots
Standard Normal Table Area Under the Curve
Chapter 5 JavaScript Numbers and Expressions
Presentation transcript:

Data Types Parsing Data JavaScript Data Types Parsing Data

Learning Objectives By the end of this lecture, you should be able to: 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.

Quick 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.

Data Types In many programming languages, every piece of data that you work with must have a declared “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: “25”  String 25  Integer 25.0  Float

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: 15.3 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.

Fascinating… um, who cares? All of this turns out to be hugely relevant in programming. The key point to note just now, 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 1. As a result we ended up with concatenation. Most definitely exam fodder here!

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….

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 not, though, your script will generate an error and your page will not display properly.

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).

Solving our earlier problem using parseInt() var age = document.getElementById('txtAge').value; //let's say the user entered 35 age = parseInt(age); var nextYear = age+1; alert("Next year you will be " + nextYear); We have solved our problem! In this case, the formula ‘age+1’ will evaluate to 36. How did it work? 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 succeed beautifully! We then take our brand-new integer 35 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.

How the code works in a little more detail 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 return 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

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". If the argument does NOT begin with a digit or a minus sign, the function will return an error. 'argument' refers to the information inside the parentheses If the argument begins with a digit or a minus sign, the function will return that value until it encounters any non-digit character. This includes a period. 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("35.3.4.5");  returns the integer 35 parseInt("I am 35 years old.");  Error – does not begin with a digit or –

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 a closely related function) a lot over the remainder of the course as well as in your exams.

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() Here is an example: var age = document.getElementById('txtAge').value; //assume the user entered "35" //Clearly we wish 'age' to hold an integer //Therefore, we must do the following: age = parseInt(age); //age can now be treated as a regular number From this point forward, i.e. throughout the remainder of the course: Whenever you read in an integer quantity from your web form, 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 not invoke the parseInt() function. The grader will deduct points every time you forget to do so! 

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 from a swimming meet where the times are often recorded to hundredths of a second. In this case, we would absolutely need to keep the decimal places. So in this case, we would use parseFloat() instead of parseInt() var raceTime = document.getElementById('txtRaceTime').value; raceTime = parseFloat(raceTime);

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.

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 name, city, 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.

Example Which of the following should be parsed? Should we use parseInt or parseFloat? The user’s age The user’s phone number The user’s birth year The user’s weight The user’s zip code Answers: parseInt() most likely. If you think there is a possibility that the user would enter an age with a decimal, then I suppose you could use parseFloat(). Neither. 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. Neither. Other than sorting (which you can do with strings), there is no “math” I can envision being done on a zip code!

File: parse_example.htm <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Parse Example</title> <script type="text/javascript"> 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> <hr> <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>

Examples File: fahrenheit_celcius_converter.htm File: bmi_calculator.htm