Working with Numbers parseInt() and parseFloat() Math.round() Other Math object functions isNaN() toFixed()

Slides:



Advertisements
Similar presentations
Modifying existing content Adding/Removing content on a page using jQuery.
Advertisements

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.
Introduction to Computing Concepts Note Set 7. Overview Variables Data Types Basic Arithmetic Expressions ▫ Arithmetic.
Form Validation. Learning Objectives By the end of this lecture, you should be able to: – Describe what is meant by ‘form validation’ – Understand why.
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
CSC1016 Coursework Clarification Derek Mortimer March 2010.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
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.
Lesson 4: Percentage of Amounts.
Binary Arithmetic Math For Computers.
Introduction to scripting
Random Stuff Colors Sizes CSS Shortcuts. Learning Objectives By the end of this lecture, you should be able to: – Identify the 3 most common ways in which.
While Loops and Do Loops. Suppose you wanted to repeat the same code over and over again? System.out.println(“text”); System.out.println(“text”); System.out.println(“text”);
Programming For Nuclear Engineers Lecture 12 MATLAB (3) 1.
Computer Science 1000 Spreadsheets II Permission to redistribute these slides is strictly prohibited without permission.
JQuery and Forms – Part I. Learning Objectives By the end of this lecture, you should be able to: – Retrieve the values entered by a user into a form.
Using the API. Learning Objectives By the end of this lecture, you should be able to: – Identify what is meant by an ‘API’ – Know how to look up functions.
06/10/ Working with Data. 206/10/2015 Learning Objectives Explain the circumstances when the following might be useful: Disabling buttons and.
Copyright ©2005  Department of Computer & Information Science Using Number & Math Objects.
Unit 3: Java Data Types Math class and String class.
DHTML AND JAVASCRIPT Genetic Computer School LESSON 5 INTRODUCTION JAVASCRIPT G H E F.
5 BASIC CONCEPTS OF ANY PROGRAMMING LANGUAGE Let’s get started …
1 Κατανεμημένες Διαδικτυακές Εφαρμογές Πολυμέσων Γιάννης Πετράκης.
Math With Java The Math Class. First, A Quick Review of Math Operators in Java Primitive Data type in Java that represent numbers: Primitive Data type.
Working with Files. Learning Objectives By the end of this lecture, you should be able to: – Examine a file that contains code with unfamiliar material,
Introducing JavaScript. Goals By the end of this lecture you should … Be able to describe the differences among object methods, object properties and.
Basic Data Types Numbers (integer and floating point)‏ Strings (sequences of characters)‏ Boolean values (true/false)‏
Return values Efficiency in Coding. Learning Objectives By the end of this lecture, you should be able to: – Be able to apply an ‘object literal’ when.
CSD 340 (Blum)1 Starting JavaScript Homage to the Homage to the Square.
1 FUNCTIONS - I Chapter 5 Functions help us write more complex programs.
Asking the USER for values to use in a software 1 Input.
Variables and Data Types Data (information we're going to store) – Numbers – Text – Dates What types of data can JavaScript process? How do we store it?
1 A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 5 JavaScript.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Modifying HTML attributes and CSS values. Learning Objectives By the end of this lecture, you should be able to: – Select based on a class (as opposed.
Working with Strings. Learning Objectives By the end of this lecture, you should be able to: – Appreciate the need to search for and extract information.
CSD 340 (Blum)1 Starting JavaScript Homage to the Homage to the Square.
The Math Class Methods Utilizing the Important Math Operations of Java!
1 Chapter 3 – Examples The examples from chapter 3, combining the data types, variables, expressions, assignments, functions and methods with Windows controls.
Debugging, Escape Command, More Math. It’s your birthday!  Write a program that asks the user for their name and their age.  Figure out what their birth.
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Variables.
Events Part I Mouse Events. Learning Objectives By the end of this lecture, you should be able to: – Understand what is meant by an ‘event’ – Appreciate.
Functions.  Assignment #2 is now due on Wednesday, Nov 25 th  (No Quiz)  Go over the midterm  Backtrack and re-cover the question about tracing the.
Changing HTML Attributes each() function Anonymous Functions $(this) keyword.
Variables and Strings. Variables  When we are writing programs, we will frequently have to remember a value for later use  We will want to give this.
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.
Expressions and Data Types Professor Robin Burke.
Checking If User Input Is Numeric.  Quiz  Detecting numeric input  Finish Prior Lecture  Y'all work on one of the problems listed 2.
CS 115 Lecture 5 Math library; building a project Taken from notes by Dr. Neil Moore.
JavaScript Part 1 Introduction to scripting The ‘alert’ function.
JavaScript: Conditionals contd.
Moving away from alert() Using innerHTML Using an empty div section
Predefined Functions Using the JavaScript Documentation
2.5 Another Java Application: Adding Integers
Data Types Parsing Data
Conditions and Ifs BIS1523 – Lecture 8.
WEB PROGRAMMING JavaScript.
Removing events Stopping an event’s normal behavior
Coding Concepts (Data- Types)
We are starting JavaScript. Here are a set of examples
'Boolean' data type.
Introducing JavaScript
Events Part III The event object.
Random Stuff Colors Sizes CSS Shortcuts.
Using the API.
Working with Numbers parseInt() and parseFloat() Math.round()
Retrieving information from forms
Presentation transcript:

Working with Numbers parseInt() and parseFloat() Math.round() Other Math object functions isNaN() toFixed()

Learning Objectives By the end of this lecture, you should be able to: – Recognize in which cases the parseInt and parseFloat functions will return a number, and when they will return ‘NaN’ – Describe what ‘NaN’ is – Invoke and make use of the isNaN() function – Be able to look up the API of the Math object and learn/apply some of the available functions – Use the toFixed() function

Be sure to review: Numeric Datatypes Recall the various data types we have discussed in the past: Strings (made up of text), Integers (whole numbers), and Floats (decimal numbers). In programming, it is vital that you are aware of some of the key issues that arise when dealing with different datatypes. If you have forgotten or are not familiar, be sure to review lectures in a previous JavaScript course that cover these topics.

A more detailed look at the parseInt() function The parseInt() function takes a string as its argument and will try to convert that string to a number. It will then return the number. You do remember what it means for a function to ‘return’ a value, right?? If you don't remember, that's okay…. BUT do NOT move on! Spend a few minutes going back and reviewing that concept. The parseInt() function works as long as the string begins with a number. (It will also work if the beginning of the string is a minus sign or a plus sign). The function will then continue to look for numbers until it finds the first character that is not a digit. At that point, the function will return all of the digits as a number instead of a string. If the function is unable to do the conversion, it will return the error ‘ NaN ’ which stands for ‘Not a Number’. Predict the value stored in ‘x’ for each of the following: var x = parseInt("10 years old"); //parseInt function returns the integer 10, so x is set to 10 var x = parseInt("-10 years old"); //parseInt function returns the integer -10, x is set to -10 var someString = "10.7 years old"; var x = parseInt(someString); //function returns the integer 10; x is set to 10 //Recall that parseInt stops at the first non-digit (including period) var x = parseInt("ten years old"); //function returns the error message ‘NaN’

Pop-Quiz What will be output by the following snippet of code? var q = " and lots of other numbers"; var x = parseInt(q); var y = x*2; alert(y); Answer: It will output -8 The parseInt() function will return -4 since it strips off everything after the first non-digit, in this case, the period. Also note that the parseInt function does NOT round! It simply chops off everything after the first non-digit. We then double ‘q’ to -8 and assign the value to ‘y’.

What’s up with the second argument to parseInt() ? You may recall that we have also used a version of parseInt() that accepts two arguments. The second argument was the integer ‘10’. (e.g. parseInt("25 years old", 10 ); The second argument tells JS that we are using a base-10 numbering system instead of something called ‘octal’. By including the 10 as the second argument, you make absolutely sure that JS knows you want a standard base-10 response. Some references imply that this second argument is obligatory. The truth is that pretty much any browser worth it’s salt will default to base-10. So you only need to include the second argument if you anticipate that some of your users might be using very old browsers. Another time you may want to use the second argument is in the rare occasion when you need an octal value returned. For most people, this will occur roughly 0.00% of the time. Pop-Quiz: Suppose I hadn’t included this slide and you wanted to find out just what was going on with that weird ‘10’. How would you have gone about it? Answer: You would have looked it up in the API documentation! Of course, because this is a JavaScript function (not a jQuery function), you’d have to look it up in the JavaScript documentation – not the jQuery API. There are a few versions of API documentation around. Here is one from W3Schools:

parseFloat() The only difference here is that parseFloat allows a single decimal point before returning the value. So: parseFloat(" is a number"); //Returns If you’re not sure whether you need to use parseInt or parseFloat, go ahead and use parseFloat. That way, even if you do end up with an integer, the worst that will happen is that you’ll end up with a ‘.0’ at the end. var mysteryNumber = prompt("Enter a number"); var num = parseFloat(mysteryNumber); Even if the user enters an integer (as opposed to a float) of, say, 11, then the value returned by the pasreFloat function will be 11.0

The Number() function This function also converts a string to a number. In addition, it can handle both integers and floats (decimals). The downside is that if there is any non-digit (other than period) present, the function will return NaN and your script might break. For this reason, I typically recommend that you use parseInt or parseFloat. However, you should know about this function since it is widely used. There may be times when you are reasonably certain that the value that comes in will not include any non-digits. In this case, by all means, feel free to use the Number() function. API for the function Number()

The Math.round() function There are lots of other functions that work with numbers, many of which will likely be useful to you at one point or another. For example, recall that while parseInt returns a number without the decimal, it does NOT round the number up or down. For example: var age = parseInt("10.8 years old"); //age will hold the integer 10 However, you will frequently want to round the number. Fortunately, there is a function called ‘ round ()’ that does exactly that. The function is part of an ‘object’ Math (we won’t discuss objects for now). However, because the function is part of this Math ‘object’, we must precede the function name with the class name: var age = parseFloat("10.8 years old"); //age holds 10.8 age = Math.round(age) ; //age now holds 11.0 A shorter and possibly more efficient way: var age = Math.round( parseFloat("10.8 years old") ); 1.First the ‘parseFloat’ function is invoked 2.Then the ‘round’ function is invoked 3.The value is then assigned to age This shorter version is a common way of doing things, so you should review it, experiment with it, and become accustomed to it! As always, there is a tradeoff between brevity (fewer lines of code) and clarity. Brevity typically (though not always) makes your code a little faster. But if adding a little extra code makes your code much more clear, then you should consider doing so.

Other Math object functions There are numerous other functions made available to us courtesy of this ‘Math’ object. These objects give us the ability to do lots of relatively common math functions such as powers (exponents), trig functions (sin, cos, tan, etc), rounding up, rounding down, logarithms, random number generation and others. Some examples to follow in a moment, but for a quick overview, here is a screengrab from W3Schools’ API of the Math object: ef_obj_math.asp

Examples of functions from the Math object Check out the Math object in the API and try to predict the returned or outputted value for the following: Math.ceil( ); //returns 11 //Incidentally, recall that NOTHING will happen with this line of code. //In the ‘real world’ we would either output it: E.g: alert( Math.ceil( )) //or store it in a variable: E.g: var x = Math.ceil( ) Math.floor( ); //returns 2 Math.round( ); //returns 3 alert( Math.pow(2,3) ); //will output 8 //NOTE: The extra spaces are not necessary. //I’ve just put them there to help you see what is going on. alert( 5 + Math.sqrt(25) ); //will output 10 alert(Math.round( parseInt(2.999))); //Will output 2 //First parseInt() will convert to 2 //We then invoke the round() function on 2 which gives… 2.

Function toFixed() Link to API: A very convenient function for assigning a specified number of decimal places to a number. By default, this function rounds to zero decimal places. var result = ; var price = result.toFixed(); //price is set to "16" Note that we invoke this function in a slightly different way than you are used to. For example, you MIGHT be tempted to write: var result = ; var price = toFixed(result); //WRONG!!!! Instead, be sure that you precede the function name with the variable you wish to round off: var price = result.toFixed();

Function toFixed() contd A couple of other things to note: You can provide an argument to the function. This argument dictates the number of decimal places to keep. If you do not provide an argument, it defaults to 0 decimal places: var result = ; var price = result.toFixed(); //price holds “16” var price = result.toFixed(2); //price holds “16.49” This function returns a string – not a number! var result = ; var price = result.toFixed(2); alert(price+7); //will output: if you have a string on either side of ‘+’ //you do NOT get addition. Instead, you get concatenation. What’s the lesson? Well there are a few here… To begin with, be sure to check out the API when using an unfamiliar function! Another thing to remember is that you should always experiment and test your code! Finally, when dealing with numbers, always remember that you may need to invoke one of the parse functions in order for things to work properly. So if you wanted to add ‘7’ dollars to the price: var result = ; var price = result.toFixed(2); price = parseFloat(price); alert(price+7); //will output 23.49

Testing for numbers: the function isNaN() As we have discussed, we can run into trouble if we are expecting a number and we don’t get one. For example, the following code will result in your script crashing and your entire page can sometimes fail to work as a result! var number = parseInt("ten"); var doubleTheValue = number * 2; Fortunately, there is a way to test to see if a given variable is indeed a number. Recall that if you try to invoke a function that requires a number (say the parseInt() function), and the argument inside is NOT a number, then many functions will kindly return a value of ‘NaN’ The JS people have very kindly provided a function for us called isNaN(). This function examines the argument and if the value is ‘NaN’, the function returns ‘true’. Otherwise, the function returns ‘false’. As is so often the case, the best way to understand what is going on is with an example: var age = prompt("How old are you?"); if ( isNaN(age) ) alert("please give me a valid age!"); else alert("You are " + age + " years old!"); NOTE: As you have noticed, we are making frequent use of both the prompt() and alert() functions. I would like to take this point to remind you that while both of these functions are quick and easy to use, they should be reserved almost exclusively for when you are testing and experimenting with code. They do not typically have much “real world” use.