# {{{{ JavaScript - Numbers and Strings }}}}

 Types of data Numbers and mathematical functions String lengths and characters Sub-strings Example - sum digits Example - round numbers to 2 decimal places Example - Pig Latin Example - Convert Upper to Lower Start of website Alphabetical index

Summary of colours in code: green is HTML useful for JavaScript, red is JavaScript, blue is a name and everything else is grey.

## Types of data

You may not have noticed, but we have been dealing with two types of data. One is a number, as in 25 and the other is a string, like "thing". Notice that "thing" is in quotes and 25 isn't. We have to put the value of a string in quotes, since a string might contain spaces, or numbers, or special characters, as well as letters. The quotes carefully contain the whole string value and tells you where it starts and, more importantly, finishes. Another reason that you need quotes is that str="thing" means that str contains the letters t-h-i-n-g, while str=thing means that both str and thing are variables, and you are setting str equal to the contents of thing. You don't get this trouble with numbers, since they can't contain anything but numbers and a decimal point, so it's obvious where they begin and end. Also they can't be variables, since a variable name must contain at least one letter (although they may contain numbers as well, but no spaces please!)

Many programming languages are fussy as to what type a particular variable is, but JavaScript is very relaxed about this. On the whole, the computer works out for itself what data type a particular variable is, and behaves accordingly. However, sometimes it gets into a muddle.

The example below shows what can happen. (I'm afraid that my imagination is running out for variable names. You are supposed to use meaningful variable names rather than just single "a". Oh well!) I've used dynamic HTML to produce the output. The first line of the output shows what happens if you add two numbers together - what you would expect, their sum. The next concatenates (pushed together) two strings. You know they are strings since they have quotes round, even though they contains numbers. Even though the same symbol, "+", is used for add and concatenate, the computer figures out which are numbers and which are strings. However, in the next two cases, I've used "+" between a string and a number (or the other way round). The computer has scratched its head, and decided to make it a string. The last case shows how to overcome this. I've started with a string of "25", but used parseInt. This changed the string into a number, so the computer can add it to the other number rather than trying to concatenate it. Another way to change the string into a number is to multiply it by one. JavaScript always tries to be helpful, and if you're multiplying something, then it must be a number, so it makes it into a number. This is rather "punk" programming (quick and dirty!) but it works. In a similar way, to make a number into a string, add "" to it!



When defining variables, it's best to give them an initial value, partly because you know what starts off in there, but partly to remind you what you think its data type is. var thing=0 means that thing is a number, but var thing="" means that thing is a string. By the way, "" is two double quotes and is an empty string. It doesn't contain a space, it contains nothing at all. Once they're defined, then try to keep numbers as numbers. If they seem to have become a string and you want them back as a number, then use parseInt or parseFloat to do that.

By the way, data which comes in from a text box will start off as a string. If you do arithmetic to it, it will get converted to a number, but careful about the dreaded "+"! The computer could think that you're trying to join strings, and behave accordingly. This sort of bug is fairly easy to track down, once you understand what's happening, and you can see from the above examples that it's quite easy to force the data into the type you want if the computer doesn't do it for you.

I have discovered a problem with parseInt which I had better describe in case you meet it. Normally parseInt gives you the integer or whole number without a problem. However, I have found that if you try to use parseInt with a number that starts with zero, it gives a strange result. I investigated this, and apparently, for a number starting with zero, it gives the result in octal and not decimal! This is weird. Luckily it rarely happens. If you are using parseInt on a number to make it into an integer, then it won't have any leading zeroes. If you are using parseInt on a string, such as something from a text box, then people don't tend to input leading zeroes either. There is a way to force parseInt to give a value in decimal, even if it does have leading zeroes. Put ,10 inside the bracket at the end, like this example.

x = parseInt(y,10)

We have already covered the main arithmetic symbols in previous examples, but just to summarise them here:

a + b means a plus b
a - b means a minus b
a * b means a times b
a / b means a divided by b

There is one more useful symbol. "a % b" means the remainder if you divide "a" by "b". For example, "14 % 5" is 4 (since 14 = 5 * 2 + 4).

When doing arithmetic, it is sometimes useful to check that these are numbers! parseInt(..) is good for making a number into a real number, but if it isn't a number to start with, it will have the value NaN. This tests a to see if it is a number.

if (isNaN(a)) {...}

If it is, then it does the contents of the if statement.

## Numbers and mathematical functions

While there are two main divisions of data, numbers and strings, there are also two types of numbers, reals and integers. An integer is a 'whole' number, whether positive or negative. It has no decimal point. A real has a decimal point. Again, JavaScript will change your integer variable into one containing a real if the arithmetic seems to demand this - division often leads to non-whole numbers. We have already seen that parseInt makes the string into an integer, or whole number. If the string has (or might have) a decimal point, then use parseFloat instead to create a real or floating point number.

However, sometimes JavaScript's helpfulness leads you into messy looking answer. In an earlier example, converting inches to centimetres, if you entered 1.1 inches, you got an answer of 2.7940000000000005 centimetres! The reason for this is that computers do their arithmetic in binary (base 2). They convert all the numbers to binary before they start, and convert the answer back to decimal when they finish. Sometimes this process leads to these stray, tiny, inaccuracies. What we need to do is round the answer. There are several ways of rounding. You can go to the nearest whole number, which JavaScript calls Math.round(..). You can 'round up' or go to the next integer up, which JavaScript calls Math.ceil(..) ('ceil' is short for ceiling). You can 'round down' or go to the previous integer, which JavaScript calls Math.floor(..). All these are demonstrated in the example below. I have given you a number to start with, but you can change it to see different effects for different numbers. The 'positive' (or JavaScript Math.abs(..)) doesn't seem to do anything with a positive number, but try entering a minus number. The Math.random() has absolutely nothing to do with whatever you input, in fact you can see that the code doesn't use the value. It just produces a random real number between 0 and 1. We have already covered a function which will give you random integers. There are various other mathematical functions and constants. These are covered in the example webpage

I've used a SELECT here, as we need to select one option from many. This does mean that if you change the number, the code for the new number won't be actioned immediately. You'll have to select a different option, then select the one you want! You might like to think how you could avoid this. Perhaps you could put an ONKEYUP in the input textbox.

 - please select - rounded next integer previous integer positive random

## String lengths and characters

You would have thought that on the whole you could do more to numbers than strings, but in fact computer programs can have fun messing around with strings. This rather silly program reverses any string that you type in!
Type something into the first box, such as your name. Click on the button. This goes through the string one character at a time. .charAt (..) picks up a single character from the string. It then adds it to the front of the output string. This has the effect of reversing it. When you code a loop, you need to know how many times, and in this case it's the number of characters in the string, in other words the string length or xx.length.

By the way, a character is a single letter, or digit of a number, or space, or any single thing really.



## Sub-strings

Another thing you can do with strings is to search through them looking for something, and pick out sub-strings, or parts of the string. If you have a string with a number of words, you can separate out the individual words. In this example, the words are months, separated by "/". The code picks out each month, converts them to lower case, to upper case, and finally with a capital letter. You could have other separators, such as commas or spaces. You can even search for a separator which is more than one character long.

The JavaScript code for searching a string is .indexOf(separator,start position) and the result is where the separator is. The start position starts as zero (NOT one!), but as we go through the string, this will change, of course. One problem with all this is that there are six months but only five commas. What is more, you don't know that you've got to the end until half way through the loop, rather than at the begining or the end like a nicely behaved loop (I hate this type of loop!) So I find the first "/" before I start the loop. The while condition checks whether it's found a separator. The position is -1 when it can't. If we have found a "/", then the code picks out the month. That is what .substring(start position,end position) does. I then change the start position to after the "/" (I forgot to do this when I wrote this code - result an infinite loop!) I then try to find the next "/" so the code can loop back and check if there is one. If there isn't, we've found the last "/" but not yet the last month, which comes after it. So I have to do one more month, from where we got to, to the end of the string, which needs .length. Since the code requires an output in two different places, I've made it into a function. The output is quite complicated. First I make the month into lower case (.toLowerCase()), then upper case (.toUpperCase()). Then I put together the first letter from the upper case example, and the rest from lower case to make a normal way of writing the month! While this is all a little silly, it can be quite useful to change input to lower or upper case. Computers regard "A" and "a" as completely different, people don't!



Another thing to do with characters is to find the ASCII or Unicode value.

## Example - sum digits

I've been asked for some code to sum digits in a string until you end up with a single digit.For example, if you input 4532, the code calculates 4+5+3+2=14. But this is still two digits, so then 1+4=5.

There are two loops. The inner loop steps through the input string one digit at a time, and adds it to the output string. I have to be careful to make sure that I am adding numbers rather than strings by using parseInt. The outer loop checks that the answer is only one digit.

 Input: Output:
Input:

Output:

## Example - Round numbers to 2 decimal places

It's easy to round whole numbers in JavaScript - use Math.round(..). However, sometimes you want some decimal places, and, what's more, you would like a fixed number of decimal places. The example below does 2 decimal places. This means that 1.3467 will become 1.35, and 2 will become 2.00, and so on. It's surprisingly tricky, as JavaScript will make the number two into 2. So we have to put the extra zeroes in. It's not very good if you don't put in a number, mind you! But the intention is to show the function r2() which can be copied and used as you will.

 Input number: Output:
Input number:

Output:

## Example - Pig Latin

Pig Latin is a mock-language. To translate each English word into a Pig Latin word, place the first letter of the English word at the end of word and add the letters "ay" e.g jump = umpjay. I have been asked for a piece of code to do this. The code below uses a string feature called 'split'. The line

var word = document.conv.english.value.split (" ")

takes the input from the form 'conv', text box 'english' and splits it into individual words (which are terminated with a space) which it puts into an array called 'word' - quite a hard-working statement! The rest of the code does the Pig Latin conversion using sub-strings, and outputs it to another text box. This won't work if people use a capital letter or any punctuation of course!


Input:

Output:

## Example - Convert Upper to Lower Case

There are times when you have a lot of text which is upper case when you want it to be lower case, or possibly mostly lower case with initial capitals. This piece of JavaScript will do that for you. It is similar to the sub-strings code above, but more generalised. Converting to lower case can be done with a single instruction. It takes a little more effort to search through the strings for spaces, so you can make the next letter into a capital.

 Enter text: All lower case: Capitals:
Enter text:

All lower case:

Capitals: