Dealing with Numbers


Computers have been used for numbers much longer than they've been used for strings, and as a result, there are lots of different ways of storing numbers in memory – all of which use memory in a different way. There are whole numbers (1, 2, 100, 543), which are known as integers, and numbers with decimal points (such as 1.2, 1.5343, 654.78), which are known as floating point numbers.

When you ask Visual Basic .NET to create a number for you, it likes to know what sort of size number you'll be creating, so that it can allocate the right amount of memory. Although Integer is the general-purpose whole number, you can have them Short or Long if you want. And for fractions, you have Decimal for numbers with only a few figures after the decimal point, Single for numbers which need to be remembered more precisely, and Double for super-accurate numbers.

You might read in other programming books, or hear from other programmers, that you should use numbers as much as possible because they are more efficient than strings. They are more efficient, but they can also be a real pain. I only use numbers when I plan to use the data as a number – to perform mathematical calculations on it, for example. If you are capturing credit card details, telephone numbers, or anything else where you really just want a sequence of digits, strings are probably better.

I've never regretted choosing a string – but I've often tried to do things the 'efficient' way using numbers, and ended up wasting hours on extra bug fixes and validation routines. On the Web, the string is the king, in general of course!

Numbers do have their place though, and it's a very important one. They are useful for counting things, looping, and doing math. So let's find out about how to use them.

Using Whole Numbers

Most of the time when you use whole numbers, you'll just use an integer without giving it a lot of thought. An Integer can store any whole number between 2,147,483,647 and 2,147,483,648. This is a large enough range for most purposes.

If you are using a lot of numbers, and they aren't all that big, you might want to try using a Short instead. This can hold a whole number between 32,767 and 32,768, and takes up about half the amount of memory.

If you need to store something really big, you could try a Long variable. This can store any whole number between 9,223,372,036,854,775,807 and –9,223,372,036,854,775,808 (about nine million, million, million; is there even a word for that amount?!). A Long variable takes up about twice as much space in memory as an Integer.

Despite the difference in size, what you can do with them remains the same whether it's a Short, Integer, or Long number.

More Precise Number Types

If you want to go beyond whole numbers, then you can choose from three floating-point number types. These are:

  • Decimal – Useful for financial calculations, and other general floating-point work

  • Single – Can store a larger number than Decimal or can store a number of the same size, but to a greater degree of accuracy

  • Double – Can store an even larger number than Single or can store a number of the same size, but to even more accurately

Understanding how floating point numbers work can be quite hard because they are limited by the simple size range (which means the potential number of zeroes both before and after the decimal point), and the level of accuracy. This rarely has practical implications, because very big numbers usually require less accuracy than very small ones. For most purposes understanding the mechanics is not very important. Just stick with Decimal, or Single if you're not worried about accuracy, and you are very, very unlikely to have any problems – unless you are trying to write a program to control a nuclear reactor or something.

Declaring Numbers

Declaring number variables is easy – just follow the tried and tested formula of using Dim, like the following:

 Dim mySavings As Decimal   'floating point number Dim myOverDraft As Single  'bigger floating point number Dim unitsSold As Long      'huge whole number Dim pages As Short         'smaller whole number 

You can assign values to them just as easily:

 mySavings = 43.50 pages = 600 

Note that numeric literals do not require quote marks. This is because Visual Basic .NET does not allow names to start with numbers, so anything that begins with a number must be a literal.

Working with Numbers

Any programming language will let you do some pretty powerful stuff with numbers. For our purposes though, we don't need to think about trigonometry or calculating square roots. Let's see how to carry out basic math with Visual Basic .NET

Adding and subtracting is easy, you just use + and -:

 mySavings = mySavings + myRoyalty 

or something like:

 myOverDraft = myOverdraft – myRoyalty 

Unfortunately, the keyboard doesn't have a good multiply and divide sign, so the designers of programming languages need to improvise. The Visual Basic .NET designers chose * for multiplying (it is quite close to the multiplication sign) and / to divide (because it looks like the stroke of a written fraction).

Another arithmetic trick is to do integer division. You do this by using \ instead of /. It's much faster than normal division, and guarantees you a whole number as the answer (it just cuts of anything after the decimal point).

One very useful bit of math on the Web is checking credit card numbers. Every credit card number has a built-in checksum, or check number, which helps retailers to spot mistakes in the quoted credit card number. We can use this method to get a pretty good idea of whether a credit card number has been entered correctly – although it's far from foolproof. This will involve some string manipulation too, so watch carefully.

Try It Out—Checking Credit Cards

This is probably the most powerful program you've written so far. Please stick with it. It will show you how to use many of the techniques we've learned so far in the book, and you'll be left with a function that will be very useful once you get into writing e-commerce sites.

  1. Create a new ASP.NET page as usual and call it Numbers.aspx. Set up the page's interface to look like the following screenshot, by using some text, a TextBox, a Button, and a Label control:

    click to expand

    Clear the Label's Text property and change the Button's Text property to Check Card Number.

  2. We're going to use some stepwise refinement to make this program easier to read and more useful. Double-click on the the button, and add the following code to the handler:

    Sub Button1_Click(sender As Object, e As EventArgs)  If ValidateCard(TextBox1.Text) Then  Label1.Text = "That'll do nicely sir!"  Else  Label1.Text = "There's nothing for you here!"  End If End Sub

    As you can see, this code is pretty easy to understand – any programmer can look at the procedure, and quickly see that this button validates the card number. You can easily see the message that comes back if the user gets the number wrong, and you can make it more polite if you want. Unfortunately, Visual Basic .NET doesn't already know how to validate credit cards, so we need to write that function ourselves.

  3. In the space above the Button1_Click procedure, add the ValidateCard() function:

     Function ValidateCard(cardNumber As String) As Boolean  ' Reverse order  Dim reverseNumber As String  Dim ch As Char  For Each ch in cardNumber  reverseNumber = ch & reverseNumber  Next  ' Double every other number  Dim doubledAlternates As String  Dim thisDigit, index As Integer  For index = 1 to reverseNumber.Length  thisDigit = CInt(reverseNumber.SubString(index - 1, 1))  If index mod 2 = 0 Then  thisDigit = thisDigit * 2  End If  doubledAlternates = doubledAlternates & thisDigit  Next  ' Add every single figure together  Dim sum As Integer  For index = 1 to doubledAlternates.Length  sum = sum + CInt(doubledAlternates.SubString(index - 1, 1))  Next  ' If sum is divisible by ten, and not zero, then you're through  ValidateCard = sum <> 0 AND sum mod 10 = 0 End Function 

  4. Press F5 to run the program, and try typing different numbers into the TextBox. It does have to be a number – you can't have spaces, or the function won't work. For nearly every number you try, you should be told that the storeowner doesn't really want to serve you. Now find a credit or debit card, and type the number from that in. The result should be much more positive. (If you're worried about typing your card number here, you don't need to be. If you're still worried, find somebody else's card and use that!)

How It Works

Let's go through and look at exactly what happens when you click the button on the page. First of all, ASP.NET automatically calls the Button1_Click procedure, which consists of a simple If ... Then ... Else block:

  If ValidateCard(TextBox1.Text) Then     Label1.Text = "That'll do nicely sir!"   Else     Label1.Text = "There's nothing for you here!"   End If

The condition for this If ... Then ... Else block is actually a function call. To understand how this works, let's look at the function's definition:

Function ValidateCard(cardNumber As String) As Boolean

You can see from this that the ValidateCard() function returns a Boolean. A Boolean is the simplest variable in programming; it has only two possible values – true or false. If a function returns a Boolean, then it can be used as the condition in a decision-making statement. What we're saying is "if the card is valid then be nice, otherwise be rude". Of course, the computer needs to know how to check if the card is valid, which is exactly what we do in the body of the ValidateCard() function.

Looking at the argument defined in our Function definition, even though the argument is a credit card number, I've chosen to use a string to store our number. This is because a credit card number is not really a number as we understand it. You never add two credit card numbers together, or subtract one from another, or divide a credit card number by two. A credit card number is really a sequence of digits, and a string is the best way to represent a sequence of digits. We're going to find this is especially true now, because we're going to be treating the credit card number as a sequence of individual digits, and not as a single, big number.

Credit card numbers are created to follow a special (and quite complicated) formula. This function is going to check that cardNumber obeys this formula. The first stage is to reverse the number. The following For Each loop goes through cardNumber character by character from start to finish, and adds each character it meets to the beginning of another string. The result is that a cardNumber value of 1234567 becomes a reverseNumber value of 7654321:

  ' Reverse order   Dim reverseNumber As String   Dim ch As Char   For Each ch in cardNumber     reverseNumber = ch & reverseNumber   Next

The next step is to work through each digit, doubling the second, fourth, sixth, eight, and so on. Every alternate digit is doubled in size, so 7654321 becomes 71258341:

  ' Double every other number   Dim doubledAlternates As String   Dim thisDigit, index As Integer   For index = 1 to reverseNumber.Length     thisDigit = CInt(reverseNumber.SubString(index - 1, 1))     If index mod 2 = 0 Then       thisDigit = thisDigit * 2     End If     doubledAlternates = doubledAlternates & thisDigit   Next 

There are two things here that we haven't seen before. The first is the Length property of a String variable. This simply tells us how long the string is ('7654321' is 7 characters long). Using this means that the For loop will go around once for each character in the string. The reason for doing this, instead of using For Each again, is that we need to know exactly what position in the string we have reached at any time.

Important

Remember that string indexes are zero-based. In other words, a 7-character string consists of character positions 0-6. Our loop counts from 1-7, so we need to subtract 1 from the loop's index to get to the correct position in the string. Alternatively, we could have looped from 0 to reverseNumber.Length 1 and not subtracted 1 within the loop. The final effect would be the same.

The second thing we have that's new is the mod operator. This is a math operator that works out the remainder you'd get if you divided one number by another. You can find out if something is an even number because if you mod it by two you will get no remainder – so we use it to find out if we are on an even-positioned character (in other words, the second, fourth, sixth, and so on)

We end up with another string called doubleAlternates – which if we started with 1234567 will be 71258341. The next step is to add every digit in this string together. This is a much simpler step:

  ' Add every single figure together   Dim sum As Integer   For index = 1 to doubledAlternates.Length     sum = sum + CInt(doubledAlternates.SubString(index - 1, 1))   Next

We keep doing an integer add of the current digit to the running sum total. So in our little example we'll have 7 + 1 + 2 + 5 + 8 + 3 +4 + 1, which gives a sum of 31.

Credit card numbers are designed in such a way that, by the end of this process, you'll have a number that ends in zero (but isn't zero itself). Here's the line that checks whether this is the case:

  ' If sum is divisible by ten, and not zero, then you're through   ValidateCard = sum <> 0 AND sum mod 10 = 0 

As you know, when you assign a value to a variable, the data type of the variable on the left of the equals sign needs to be compatible with the data type of the expression on the right. ValidateCard was defined As Boolean, so the type on the left is a Boolean – a true/false value. The expression on the right needs to boil down to a Boolean too – and it does. It's saying "if sum isn't zero, and if sum does divide by 10 without a remainder" then ValidateCard should be true. If not, ValidateCard should be false.

Note

This is a very useful and quick way of checking for mistakes in credit card numbers. However, it does not guarantee that the credit card number is genuine. With a bit of thought, anybody could make up a number that obeyed these rules. If you are accepting credit card payments, you need to be much more certain than this that the card number is genuine. You can do this by using a credit card processing company, which can check that the card really does exist, that it has funds available, and even that the name and address match those given by the user.

Once this has been worked out, the Button1_Click procedure will display either the polite or rude message – in our example it will be a rude one. Sorry to do that to you – but I'm not going to tell you my credit card number just so that you can see a polite message.

The Boolean type was a new concept in the above example so let's have a proper look at the Boolean data type.




Beginning Dynamic Websites with ASP. NET Web Matrix
Beginning Dynamic Websites: with ASP.NET Web Matrix (Programmer to Programmer)
ISBN: 0764543741
EAN: 2147483647
Year: 2003
Pages: 141

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net