home account info subscribe login search My ITKnowledge FAQ/help site map contact us


 
Brief Full
 Advanced
      Search
 Search Tips
To access the contents, click the chapter and section titles.

Visual Basic 6 Black Book
(Publisher: The Coriolis Group)
Author(s): Steven Holzner
ISBN: 1576102831
Publication Date: 08/01/98

Bookmark It

Search this book:
 
Previous Table of Contents Next


Converting Strings To Numbers And Back Again

You’re all set to write your SuperDeluxe calculator program in Visual Basic—but suddenly you realize that the user will be entering numbers in text form, not in numeric form. How can you translate text into numbers, and then numbers into text to display your results?

It’s common in Visual Basic to have to convert values from numbers to strings or from strings to numbers, and it’s easy to do. You can use the Str() to return a string representation of a number, and you use Val() to convert a string to a number. That’s all there is to it, but it’s easy to forget those two functions, so we include them here for reference.

Besides Str() and Val(), you can also use Format(), which lets you format an expression into a string this way:

Format (expression [, format[, firstdayofweek[, firstweekofyear]]])

Here, expression is the expression to format into the string, format is a valid named or user-defined format expression, firstdayofweek is a constant that specifies the first day of the week, and firstweekofyear is a constant that specifies the first week of the year.

For more information about how to use this function and format strings, see “Handling Dates And Time Using Dates” later in this chapter.

Handling Operators And Operator Precedence

You’ve done well in your computer class—so well that the instructor has asked you to calculate the average grade on the final. Nothing could be easier, you think, so you put together the following program:

Private Sub Command1_Click()
    Dim intGrade1, intGrade2, intGrade3, NumberStudents As Integer
    intGrade1 = 60
    intGrade2 = 70
    intGrade3 = 80
    NumberStudents = 3
    MsgBox ("Average grade = " &_
        Str(intGrade1 + intGrade2 + intGrade3 / NumberStudents))
End Sub

When you run the program, however, it calmly informs you that the average score is 156.66666667. That doesn’t look so good—what’s wrong?

The problem lies in this line:

Str(intGrade1 + intGrade2 + intGrade3 / NumberStudents))

Visual Basic evaluates the expression in parentheses from left to right, using pairs of operands and their associated operator, so it adds the first two grades together first. Instead of adding the final grade, however, it first divides that grade by NumberStudents, because the division operation has higher precedence than addition. So the result is 60 + 70 + (80/3) = 156.66666667.

The solution here is to group the values to add together this way using parentheses:

Private Sub Command1_Click()
    Dim intGrade1, intGrade2, intGrade3, NumberStudents As Integer
    intGrade1 = 60
    intGrade2 = 70
    intGrade3 = 80
    NumberStudents = 3
    MsgBox ("Average grade = " &_
        Str((intGrade1 + intGrade2 + intGrade3)/ NumberStudents))
End Sub

Running this new code gives us an average of 70, as it should be.

This example points out the need to understand how Visual Basic evaluates expressions involving operators. In general, such expressions are evaluated left to right, and when it comes to a contest between two operators (such as + and / in the last term of our original program), the operator with the higher precedence is used first.

Visual Basic’s operator precedence, arranged by category, appears in Table 3.6.

Table 3.6 Operators and operator precedence.
Arithmetic Comparison Logical
Exponentiation (^) Equality (=) Not
Negation (-) Inequality (<>) And
Multiplication and division (*, /) Less than (<) Or
Integer division (\) Greater than (>) Xor
Modulus arithmetic (Mod) Less than or equal to (<=) Eqv
Addition and subtraction (+, -) Greater than or equal to (>=) Imp
String concatenation (&) Like Is

When expressions contain operators from more than one category in Table 3.6, arithmetic operators are evaluated first, comparison operators are evaluated next, and logical operators are evaluated last. Also, comparison operators actually all have equal precedence, which means they are evaluated in the left-to-right order in which they appear.

If in doubt, use parentheses—operations within parentheses are always performed before those outside. Within parentheses, however, operator precedence is maintained.

Using If…Else Statements

The If statement is the bread and butter of Visual Basic conditionals, but you can forget the syntax every now and then (that is, is it ElseIf or Else If?), so here’s the If statement:

If condition Then
[statements]
[ElseIf condition-n Then
[elseifstatements]]...
[Else
[elsestatements]]
End If

And here’s an example showing how to use the various parts of this popular statement:

Dim intInput
intInput = -1

While intInput < 0
    intInput = InputBox("Enter a positive number")
Wend

If intInput = 1 Then
    MsgBox ("Thank you.")
ElseIf intInput = 2 Then
    MsgBox ("That's fine.")
ElseIf intInput >= 3 Then
    MsgBox ("Too big.")
End If

Using Select Case

You have to get a value from the user and respond in several different ways, but you don’t look forward to a long and tangled series of If…Then…Else statements. What can you do?

If your program can handle multiple values of a particular variable and you don’t want to stack up a lot of If…Else statements to handle them, you should consider Select Case. You use Select Case to test an expression, seeing which of several cases it matches, and execute the corresponding code. Here’s the syntax:

Select Case testexpression
[Case expressionlist-n
[statements-n]] ...
[Case Else
[elsestatements]]
End Select


Previous Table of Contents Next


Products |  Contact Us |  About Us |  Privacy  |  Ad Info  |  Home

Use of this site is subject to certain Terms & Conditions, Copyright © 1996-2000 EarthWeb Inc.
All rights reserved. Reproduction whole or in part in any form or medium without express written permission of EarthWeb is prohibited.