Working with Numbers parseInt() and parseFloat() Math.round()

Slides:



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

Escaping Characters document.write(). Learning Objectives By the end of this lecture, you should be able to: – Recognize some of the characters that can.
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.
Working with Numbers parseInt() and parseFloat() Math.round() Other Math object functions isNaN() toFixed()
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.
Copyright ©2005  Department of Computer & Information Science Using Number & Math Objects.
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.
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.
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?
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.
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.
Checking If User Input Is Numeric.  Quiz  Detecting numeric input  Finish Prior Lecture  Y'all work on one of the problems listed 2.
© 2010 Robert K. Moniot1 Chapter 6 Introduction to JavaScript.
JavaScript Part 1 Introduction to scripting The ‘alert’ function.
Few More Math Operators
JavaScript: Conditionals contd.
JavaScript Controlling the flow of your programs with ‘if’ statements
Precedence Operators Error Types
Moving away from alert() Using innerHTML Using an empty div section
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
Regular Expressions 'RegEx'.
Chapter 6 JavaScript: Introduction to Scripting
Predefined Functions Using the JavaScript Documentation
Introduction to Python
CS005 Introduction to Programming
Concatenation Comments
Formatting Output.
Android 11: The Calculator Assignment
2.5 Another Java Application: Adding Integers
Project 9 Creating Pop-up Windows, Adding Scrolling Messages, and Validating Forms.
EGR 2261 Unit 4 Control Structures I: Selection
CS1371 Introduction to Computing for Engineers
Retrieving information from forms
Modified from Sharon Guffy
Intro to PHP & Variables
IPC144 Introduction to Programming Using C Week 2 – Lesson 1
Data Types Parsing Data
Lesson 2: Building Blocks of Programming
Working with Text and Numbers in Java
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
Conditions and Ifs BIS1523 – Lecture 8.
Number and String Operations
WEB PROGRAMMING JavaScript.
CISC101 Reminders Assn 3 due tomorrow, 7pm.
Removing events Stopping an event’s normal behavior
Introduction to TouchDevelop
Coding Concepts (Data- Types)
Variables, Types, Operations on Numbers
Variables Kevin Harville.
We are starting JavaScript. Here are a set of examples
JavaScript Variables.
'Boolean' data type.
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
Introducing JavaScript
Data Types Every variable has a given data type. The most common data types are: String - Text made up of numbers, letters and characters. Integer - Whole.
Introduction to C Programming
Events Part I Mouse Events.
Working with Strings.
Events Part III The event object.
Modifying HTML attributes and CSS values
JavaScript Variables.
Random Stuff Colors Sizes CSS Shortcuts.
Using the API.
JavaScript Part 2 Organizing JavaScript Code into Functions
Retrieving information from forms
Data Types Parsing Data
Chapter 5 JavaScript Numbers and Expressions
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 = "-4.999 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: http://www.w3schools.com/jsref/jsref_parseInt.asp

parseFloat() The only difference here is that parseFloat allows a single decimal point before returning the value. So: parseFloat("3.1415.9999 is a number"); //Returns 3.1415 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 parseFloat 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() http://www.w3schools.com/jsref/jsref_Number.asp

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") ); First the ‘parseFloat’ function is invoked Then the ‘round’ function is invoked 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: http://www.w3schools.com/jsref/jsref_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(10.00001); //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(10.00001)) //or store it in a variable: E.g: var x = Math.ceil(10.00001) Math.floor(2.999999); //returns 2 Math.round(2.99999); //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 2.999 to 2 //We then invoke the round() function on 2 which gives… 2.

Function toFixed() Link to API: http://www.w3schools.com/jsref/jsref_tofixed.asp 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 = 16.492234; 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 price = toFixed(result); //WRONG!!!! Instead, be sure that you precede the function name with the variable you wish to round off:

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 = 16.492234; 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 price = result.toFixed(2); alert(price+7); //will output: 16.497 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: 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.