CONVERTING A STRING TO A NUMBER
Here is a quick question. What do you think will be the typeof the following variable:
But what if you wanted that variable to be recognized as a number instead of a string? Well, that is where parseInt(); function comes to play. So before you can perform arithmetic operations on a group of numbers, you need to know you're dealing with numbers!
parseInt's duty is to convert a string into an integer. It starts this process from the left hand side, and begins converting digits until it runs into a non numerical digit. From this point, the process will stop. Whatever has been converted will automatically be assigned to the variable. If the first character encountered is not a numerical value, then parseInt will display "NaN" - which stands, for not a number.
Now a practice use for parseInt would be if you are using numerical values obtained from user input. So, if they enter, "stupid" instead of a #, you can test with parseInt if it is indeed a number, and if not, re-prompt them to enter a value.
Here is an example of how parseInt(); will work:
As you might see in var1 and var2, parseInt stopped after "7" in var1 because of the "U", and in var2, it stopped after the "7" because of the "U". In var3, it saw the "W" and saw it was not a number (NaN). For var4, it stopped after the number "3" because of the "A", even though after "ABC" numbers pick back up- parseInt stops after the first non numeric digit, not all digits within the variable. var5 stopped when it saw the "." because it is a non numeric digit as well.
What you needed to recognize floating point numbers? Well, this is where the parseFloat(); function comes into action. parseFloat works exactly like parseInt, except it works with floating point numbers instead of just integers. So when parseFloat comes to a period "." it will interpret it as a decimal point (where parseInt saw it as a non numeric digit). However, if a second period is noticed, parseFloat will see it as a non numeric digit.
CONVERTING NUMBERS TO STRINGS
Ok, working opposite now. What if we have a number, and want to make it a string? Well, we are lucky that JavaSript has the toString(); function! How you will use this, is by simply adding the toString(); function at the end of your variable name seperating the variable and function with a period.
There is also another way to turn a number into a string, and that is by adding double quotes to it. We will do that by using the method outlined within the code in the example below:
There you have it. Now you know how to convert a number to a string.
Date: Feb 20 2009 at 11:50 pm
I assume should
NG STRINGS TO
What if we have
a string, and
want to make it
shows code to
take a number,
and make it a
not trying to
be picky, I'm
just trying to
make sure I