Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Working with Numbers parseInt() and parseFloat() Math.round()"— Presentation transcript:

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

2 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

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

4 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’

5 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’.

6 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:

7

8 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 parseFloat function will be 11.0

9 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()

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

11 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:

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

13 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 price = toFixed(result); //WRONG!!!! Instead, be sure that you precede the function name with the variable you wish to round off:

14 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 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: price = parseFloat(price); alert(price+7); //will output 23.49

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


Download ppt "Working with Numbers parseInt() and parseFloat() Math.round()"

Similar presentations


Ads by Google