How to Convert Strings into Numbers (And Vice Versa)

June 14th, 2008 yudi Posted in Number and Strings No Comments »

A string can consist of letters, symbols, and numbers. The most common use for storing numbers as a string is when the numbers represent something special, such as a telephone number or address. If you want the computer to print a telephone number, you must store that number as a string, as shown here:


PRINT “555-1212″

This command prints the string 555-1212 on-screen. The quotation marks tell the computer, “Anything inside the quotation marks is a string.” What happens if you try the following command?


PRINT 555-1212

Liberty BASIC interprets this command to mean, “Subtract the number 1,212 from the number 555 and print the result (which is –657) on-screen.”

Although the number 53 and the string “53” may look identical to a human, computers treat numbers as entirely different from strings. To a computer, the number 53 is as completely different from the string “53” as a painting of a cat is different from a real cat.

Converting strings into numbers

The problem with strings is that when users enter numbers, the computer may treat those numbers as strings, but your program may need to use those numbers as data. If a program stores a number as a string but needs to use that number as data, the program needs to convert that number (as a string) into data.

To convert a string into data, most programming languages come with special string-to-data and data-to-string conversion commands. In Liberty BASIC, you can convert a string into a number by using the VAL function, which works like this:


VAL(”String”)

The VAL function tells Liberty BASIC, “Take a string (such as “45”) and turn it into a number.” If you have a string “45” and use the VAL function, Liberty BASIC converts that string “45” into the number 45.

Remember If you use the VAL function on a string that doesn’t represent a number, such as the string “Hello!”, the VAL function returns a zero value.

To see how the VAL function works, run the following Liberty BASIC program:


YearBorn$ = “1964″                                ?1
PRINT “You were born in ” + YearBorn$             ?2
Age = 2007 - VAL(YearBorn$)                       ?3
PRINT “In 2007, you were this old = “; Age        ?4
END ?5

This Liberty BASIC program tells the computer to do the following:

  • ?1 Creates a string variable called YearBorn$ and stuffs it with the string “1964”.

  • ?2 Prints the string “You were born in ” followed by the string stored in the YearBorn$ variable, so the entire line prints You were born in 1964. In this line, the computer treats “1964” as a string.

  • ?3 The VAL function converts the string “1964” to the number 1964. Then it subtracts 1964 from 2007 and stores the calculated result in the Age variable.

  • ?4 Prints the string In 2007, you were this old = and then prints the number stored in the Age variable, which is 20071964 (43).

  • ?5 This line marks the end of the program.

REALbasic uses the same Val function to convert a string into data, as shown here:


Dim YearBorn as string                            ?1
Dim Age as integer                                ?2
YearBorn = “1964″                                 ?3
MsgBox “You were born in ” + YearBorn             ?4
Age = 2007 - Val(YearBorn)                        ?5
MsgBox “In 2007, you were this old = ” + Str(Age) ?6

This REALbasic program tells the computer to do the following:

  • ?1 Creates a string variable called YearBorn.

  • ?2 Creates an integer variable called Age.

  • ?3 Stores the string “1964” into the YearBorn string variable.

  • ?4 Uses the MsgBox command to display a box on-screen that shows the string “You were born in “ followed by the string stored in the YearBorn variable, so the entire line prints You were born in 1964. In this line, the computer treats “1964” as a string.

  • ?5 The Val function converts the string “1964” to the number 1964. Then it subtracts 1964 from 2007 and stores the calculated result (43) in the Age variable.

  • ?6 Uses the MsgBox command to display a box on-screen that shows the string In 2007, you were this old = and then uses the Str function to convert the Age variable (43) to the string “43”. So the entire line prints out In 2007, you were this old = 43.

One problem with type-safe languages like REALbasic is that they restrict what type of data can go into variables (to prevent errors in your program), but they can also make programming more cumbersome when you want to treat a number as both a string and data.

The following Revolution program automatically detects when a number should be treated as a string and when it should be treated as data. Although this has the potential for causing errors, it also gives you the freedom to concentrate on the logic of your program and not worry about trivial details like converting strings into data (and vice versa).


put “1964″ into YearBorn                                 ?1
put “You were born in ” && YearBorn into message         ?2
wait for 5 seconds                                       ?3
put 2007 - YearBorn into Age                             ?4
put “In 2007, you were this old = ” && Age into message  ?5

This Revolution program tells the computer to do the following:

  • ?1 Stores the string “1964” in a variable called YearBorn.

  • ?2 The two ampersand symbols (&&) tack the string “1964” onto the other string “You were born in ”. Then this line display You were born in 1964 in a message box on-screen.

  • ?3 Tells the computer to wait for five seconds. Without this command, Revolution would rush into the rest of the program and the message box displayed in line 2 would appear and disappear in the blink of an eye.

  • ?4 Automatically converts the string “1964” into the number 1964. Then subtracts the number 1964 from 2007 and stores the result (43) in a variable called Age.

  • ?5 Converts the Age variable number (43) into the string “43” and then the two ampersand symbols (&&) tack the “43” string onto the end of the “In 2007, you were this old = ” string. Then this line displays In 2007, you were this old = 43 in a message box that appears on-screen.

The main difference between Revolution and the previous two BASIC examples is that Revolution is smart enough to figure out when to treat a number as data and when to treat a number as a string without having to define any data conversion yourself.

Technical Stuff The C++ language doesn’t recognize strings as valid data types, although you can define a string data type by using the using namespace std; command at the top of your programs. However, C++ doesn’t provide any built-in commands for converting strings into numbers (and vice versa), so many programmers simply write their own conversion programs and store them in library files that they can reuse later.

Converting a number into a string

Rather than convert a string into a number, you might want to go the other way and convert a number into a string.

In Liberty BASIC, you can convert a number into a string by using the STR$ function, which works like this:


STR$ (Number)

The following Liberty BASIC program shows how to use the STR$ function to convert the BossIQ variable into a string:


BossIQ = 34                                      ?1
NewString$ = “This is the IQ of your boss = ” +
           STR$(BossIQ)                          ?2
PRINT NewString$                                 ?3
END                                              ?4

This Liberty BASIC program tells the computer to do the following:

  • ?1 Stores the number 34 in a variable called BossIQ.

  • ?2 Uses the STR$ function to convert the number stored in the BossIQ variable (34) into a string (“34”). Then it pastes the two strings together to store This is the IQ of your boss = 34 in a string variable called NewString$.

  • ?3 Prints the string This is the IQ of your boss = 34 on-screen.

  • ?4 Defines the end of the program.

In this example, Liberty BASIC lets you declare a number variable and convert that number into a string. Here’s the equivalent REALbasic program that converts a number into a string by using the Str function:


Dim BossIQ as Integer
Dim NewString as String
BossIQ = 34
NewString = “This is the IQ of your boss = ” + Str(BossIQ)
MsgBox NewString

In Revolution, you don’t need to give an explicit command to convert a number into a string; the computer does this conversion for you automatically, as the following program demonstrates:


put 34 into BossIQ
put “This is the IQ of your boss = ” && BossIQ into
           message
AddThis Social Bookmark Button

Declaring variables as strings

April 21st, 2008 yudi Posted in Number and Strings No Comments »

 

As with numbers, you can use strings directly in your program, as follows:


PRINT “Print me.”
PRINT 54
END

Just as with numbers, you may want to store strings in variables so you can reuse that particular string over and over again by typing just the variable rather than the entire string.

Unfortunately, every programming language tends to use different ways to declare a variable to hold a string data type. In Liberty BASIC, you never declare variables until you actually assign data to them. When assigning a string to a variable, the variable name must include the dollar sign ($) at the end of the variable name, as follows:


MyName$ = “Bo the Cat”

In Revolution, you can assign a string to a variable (just like you can assign a number to a variable) by using the into command like so:


put “Bo the Cat” into MyName

In REALbasic, you can declare a variable to hold string data types, as follows:


Dim MyName As String

The C++ language won’t recognize string data types, so you must use a library file called std, which you can include in your program by adding the following:


using namespace std;

This command tells your C++ program to use a library file called std, which defines a string data type. After you include the std library file, you can declare a string variable such as:


string myName;

So an entire C++ program that declares a string variable might look like this:


#include <iostream.h>
#include <stdio.h>
using namespace std;
int main()
{
   string myName;
   myName = “Bo the Cat”;
   cout << myName;
   cout << “\nPress ENTER to continue…” << endl;
   getchar();
   return 0;
}
AddThis Social Bookmark Button

Smashing strings together

April 21st, 2008 yudi Posted in Number and Strings No Comments »

Unlike with numbers, you can’t subtract, divide, or multiply strings. But you can add strings (which is technically known as concatenating strings). To concatenate two strings, you use the plus sign (+) to essentially smash two strings into a single string, as the following Liberty BASIC example shows:


MyName$ = “Joe Smith”                             ?1
PRINT “Hello, ” + MyName$                         ?2
END                                               ?3

This Liberty BASIC program tells the computer to do the following:

  • ?1 Creates a string variable called MyName$ and stuffs it with the string “Joe Smith”.

  • ?2 Prints the string “Hello, “ followed by the string stored in the MyName$ variable, so the entire line prints out Hello, Joe Smith.

  • ?3 Tells the computer that the program is at an end.

Remember If you concatenate strings, make sure that you leave a space between the two strings so that they don’t appear smashed together (likethis). In the previous example, notice the space in the second line following the word Hello and the comma.

Both REALbasic and C++ also let you use the plus sign (+) to concatenate strings. However, Revolution uses the dual ampersand symbols (&&) to concatenate strings like so:


put “Joe Smith” into MyName
put “Hello, ” && MyName into message
 
AddThis Social Bookmark Button

Using Built-In Math Functions

April 21st, 2008 yudi Posted in Number and Strings No Comments »

By combining mathematical operators, you can create practically any type of mathematical formula. But creating some mathematical formulas may prove too cumbersome, so as a shortcut, many programming languages provide built-in mathematical functions that you can use. 

Technical Stuff If you don’t understand terms like arcsine or logarithm, you probably don’t need to use them anyway. The important point to remember is that all programming languages include built-in mathematical functions that you can use if you need them.

To see how the Liberty BASIC mathematical functions work, run the following program and type different numbers (negative, positive, decimal, and so on) between 0 and 1.0 to see how the program works:

 



PROMPT “Type in a number”; AnyNumber

PRINT “The ABS value = “; ABS(AnyNumber)

PRINT “The ACS value = “; ACS(AnyNumber)

PRINT “The ASN value = “; ASN(AnyNumber)

PRINT “The ATN value = “; ATN(AnyNumber)

PRINT “The COS value = “; COS(AnyNumber)

PRINT “The EXP value = “; EXP(AnyNumber)

PRINT “The LOG value = “; LOG(ABS(AnyNumber))

PRINT “The SIN value = “; SIN(AnyNumber)

PRINT “The SQR value = “; SQR(AnyNumber)

PRINT “The TAN value = “; TAN(AnyNumber)

PRINT

END

You can use only positive numbers with the LOG function or in calculating a square root.

Technical Stuff Unlike many programming languages, C++ doesn’t have built-in math functions. Instead, C++ compilers come with a library of math functions written in C++. You don’t have to worry about how these math functions work; you can just use them by adding the #include <math.h> command at the top of your program, as shown here:

 



#include <iostream.h>

#include <stdio.h>

#include <math.h>

int main()

{

  double anyNumber;

  cout << “Enter a number: “;

  cin >> anyNumber;

  cout << “The ABS value = “; cout << abs(anyNumber);

  cout << “nThe ACOS value = “; cout << acos(anyNumber);

  cout << “nThe ASIN value = “; cout << asin(anyNumber);

  cout << “nThe ATAN value = “; cout << atan(anyNumber);

  cout << “nThe COS value = “; cout << cos(anyNumber);

  cout << “nThe EXP value = “; cout << exp(anyNumber);

  cout << “nThe LOG value = “; cout << log(anyNumber);

  cout << “nThe SIN value = “; cout << sin(anyNumber);

  cout << “nThe SQRT value = “; cout << sqrt(anyNumber);

  cout << “nThe TAN value = “; cout << tan(anyNumber);

  cout << “nThe ACOS value = “; cout << acos(anyNumber);

  cout << “nPress ENTER to continue…” << endl;

  getchar();

  return 0;

}

A mathematical function accepts a value and uses that value to calculate a result. So you can assign a mathematical function to a variable, as the following REALbasic program demonstrates:

 



Dim x, y as Single                                  ?1

x = 0.52                                            ?2

y = cos(x)                                          ?3

MsgBox str(y)                                       ?4

This REALbasic program tells the computer to do the following:

  • ?1 Declares two variables x and y that can hold only a single-precision (decimal) number.

  • ?2 Stores the value 0.52 into the x variable.

  • ?3 Gives the value 0.52 to the cosine (cos) mathematical function. The cosine mathematical function calculates the cosine of 0.52, which is 0.8678191. This value gets stored in the y variable.

  • ?4 The str command converts the number 0.8678191 into the string “0.8678191”, which it then displays in a message box created by the MsgBox command.

Mathematical functions work the same way in Revolution, as the following program shows:

 



put 0.52 into x                                   ?1

put cos(x) into y                                 ?2

put y into message                                ?3

This Revolution program tells the computer to do the following:

  • ?1 Stores the value 0.52 into a variable called x.

  • ?2 Gives the value of x (0.52) to the cosine mathematical function, which returns the value 0.876819 and stores this value in a variable named y.

  • ?3 Displays the value of the y variable on-screen in a message box defined by the message command.

AddThis Social Bookmark Button

Adding, Subtracting, Dividing, and Multiplying

February 1st, 2008 yudi Posted in Number and Strings No Comments »

The four basic ways to manipulate numbers are adding, subtracting, dividing, and multiplying. By using these four mathematical operations, you can create any type of complicated mathematical formula.

To add, subtract, divide, or multiply two numbers (or two variables that represent numbers), you use the symbols shown in Table.

Remember The division symbol ( / ) usually appears in two places on your keyboard: on the same key as the question mark (?) and on the numeric keypad. The exponentiation symbol (^) appears on the 6 key. You can also use the subtraction symbol (–) to indicate negative numbers, such as –34.5 or –90.

Although you already understand how addition, subtraction, division, and multiplication work, you may be less familiar with integer division, modulo, and exponentiation.

Integer division divides two numbers and returns only the integer portion of the result. So dividing 25 by 6 would normally give you 4.167, but with integer division, the decimal portion of the number gets chopped off, and the result is simply 4.

Modulo is a form of division that divides two numbers and returns only an integer remainder. So dividing 25 mod 6 would return 1 (because 6 goes into 25 four times, leaving a remainder of 1).

Exponentiation simply multiplies one number by itself several times. The formula 4 ^ 3 tells the computer to take the number 4 and multiply it by itself three times. So 4 ^ 3 really means 4 * 4 * 4, or 64.

Image from book

Technical StuffC++ unary operators

Mathematical operators, such as addition (+) and multiplication (*), are known as binary operators because they operate on two different values. In C++, you can also use something called unary operators, which operate on a single value. The most common C++ unary operators are ++ (which increments a value by one) and , (which decrements a value by one).

You can place a unary operator before or after a variable (for example, ++i or i++). The placement of the unary operator defines when to alter the variable. Consider the following C++ code:

 



int x;

int y;

int z;

x = 5;

y = x++  // y = 5 but x = 6

z = ++y  // z = 6 and y = 6

In the line y = x++, the value of x is 5 and is first assigned to y, which now holds the number 5. Then the ++ unary operator increments the value of x by one so x now stores the number 6. In the line z = ++y, the unary operator first increments the value of y. Because y holds the number 5, the ++ unary operator increments it to 6, and this value gets stored in the z variable.

Unary operators are often used to count in a FOR-NEXT loop although you can use them anywhere.

Image from book
AddThis Social Bookmark Button

Working with precedence

February 1st, 2008 yudi Posted in Number and Strings No Comments »

Consider the following formula, which multiples two variables and stores the result in a third variable called TaxYouOwe:


TaxYouOwe = NetIncome * TaxRate

Such a simple formula is easy to understand; you just multiply the values that both variables represent. Of course, you can create more powerful mathematical formulas by combining addition, subtraction, division, or multiplication, as in the following example:


TaxYouOwe = PastTaxes + NetIncome * TaxRate

If the value of PastTaxes is 2500, the value of NetIncome is 50000, and the value of TaxRate is 1.01, the computer looks at the formula as follows:


TaxYouOwe = 2500 + 50000 * 1.01

So now the question is what does the computer do first? Does it add 2,500 to 50,000 and then multiply the whole thing by 1.01 (in which case the answer is 53,025) or multiply 50,000 by 1.01 first and then add 2,500 (in which case the answer is 53,000)?

Because the result of combining addition, subtraction, division, and multiplication in a single formula can be so confusing, programming languages use something known as precedence, which tells the computer which mathematical operations to calculate first. Most programming languages calculate mathematical operators in the following order, from top (first) to bottom (last):

  •  Exponentiation (^)

  •  Multiplication (*) and division ( / )

  •  Integer division ( \)

  •  Modula arithmetic (mod)

  •  Addition (+) and subtraction (–)

Remember The computer always calculates operators from left to right if operators are equal in precedence, such as multiplication and division or addition and subtraction.

Before running the following Liberty BASIC program, try to figure out how the computer calculates a result:


MyMoney = 3 + 4 ^ 5 ? 8 / 5 * 7
PRINT MyMoney
END

This is how Liberty BASIC calculates the value of MyMoney:

  1. Because the computer calculates exponential values first, Liberty BASIC calculates the value of 4 ^ 5, which is 1024. The formula now looks like this:

    
    MyMoney = 3 + 1024 ? 8 / 5 * 7
  2. Next, the computer calculates all multiplication and division. Because multiplication and division have equal precedence, the computer starts calculating with the first multiplication or division operator that it finds,

    moving from left to right. The computer calculates the value of 8 / 5 first (1.6) and then multiplies it by 7. So the formula now looks like this:

    
    MyMoney = 3 + 1024 ? 11.2
  3. Finally, the computer calculates all addition and subtraction, moving from left to right. First it calculates the value of 3 + 1,024 (which is 1027), and then it subtracts 11.2 from 1027. Thus the final answer looks like this:

    
    MyMoney = 1015.8
AddThis Social Bookmark Button

Using parentheses

February 1st, 2008 yudi Posted in Number and Strings No Comments »

Trying to remember the precedence of different mathematical operators can prove confusing. Even worse is that the ordinary precedence of mathematical operators can mess up the way that you want the computer to calculate a result. Suppose that you typed the following Liberty BASIC program:


BigValue = 3 + 4 ^ 5
PRINT BigValue
END

With this program, the computer first calculates the exponential value of 4 ^ 5 (which is 1024), and then it adds 3 to it, for a total of 1027.

But what if you really want the computer to add 3 to 4 and then perform the exponential? In this case, you must use parentheses to tell the computer, “Hey, add 3 to 4 first and then calculate the exponential,” as in the following example:


BigValue = (3 + 4) ^ 5
PRINT BigValue
END

This program adds 3 and 4 to get 7, so the formula becomes BigValue = 7 ^ 5, or 16807.

Remember Anytime that the computer sees something trapped within parentheses, it calculates those values first. Then it uses its normal rules of precedence to figure out how to calculate the rest of the formula.

Tip Use parentheses to enclose only one mathematical operator at a time, such as (3 + 4). Although you can use parentheses to enclose multiple mathematical operators, such as (3 + 4 ^ 5), doing so essentially defeats the purpose of using parentheses to make clear what the computer is to calculate first. You can, of course, use multiple parentheses to create fairly complex formulas, as in the following formula:


EasyTaxCode = ((3 + 4) ^ 5 / 3 ? 8) / 5 * ?7

Without the parentheses in the preceding formula, the computer would calculate an entirely different result.

AddThis Social Bookmark Button




eXTReMe Tracker