Working with Numeric Data Types

function OpenWin(url, w, h) { if(!w) w = 400; if(!h) h = 300; window.open(url, "_new", "width=" + w + ",height=" + h + ",menubar=no,toobar=no,scrollbars=yes", true); } function Print() { window.focus(); if(window.print) { window.print(); window.setTimeout('window.close();',5000); } }
Team-Fly    

Special Edition Using Microsoft® Visual Basic® .NET
By Brian Siler, Jeff Spotts
Table of Contents
Chapter 6.  Storing Information in Variables


There are a variety of types used for storing numeric data. In math, numbers can either be whole or fractional. Whole numbers, such as years or ages, can be stored in variables of type Short, Integer, or Long. Numbers with decimal places, such as monetary values or scientific measurements, can be stored in Decimal, Single, or Double variables. The following lines of code demonstrate assigning numbers to the various numeric data types:

 Dim SelectedYear As Short = 1999  Dim USPopulation As Integer = 283727132  Dim WorldPopulation As Long = 6132426512  Dim ShoeSize As Single = 1234.5E-2  Dim Temperature As Double = 98.6  Dim CostOfDoingBusiness As Decimal = 59.95D  Dim SerialNumber As Decimal = 90125 

Notice we included two examples of assigning a value to a Decimal variable. The Decimal type can store decimals or whole numbers. However, Visual Basic by default assumes numbers typed with decimal places are single or double, so we added the D character to indicate the value 59.95 is a decimal value. The D is an example of a literal type character, which helps Visual Basic determine what type of value a literal number in your code represents. The other type characters are listed next:

Character

Data Type

F

Single(Floating point)

D

Decimal

I

Integer

L

Long

R

Double

S

Short

These literal type characters are necessary only when you type numbers directly in your program and Visual Basic does not choose the correct data type. As you will see in upcoming sections, numeric variables are also used to store the result of a mathematical calculation or the contents of another variable.

Bits, Bytes, and Storage Space

The memory required for a given data type varies with the range of numbers it can store. As you saw in Table 6.2, memory requirements for data storage are measured in bytes, which is itself a data type. To be as efficient as possible, do not choose a data type that is too large for what you intend to store. At their most basic level, computers work with bits, which are 1's and 0's that represent the on-or-off status of an electronic circuit. 8 bits together make up a byte. For example, the following binary bit pattern represents the number 171:

 10101011 

Starting from right and moving left, each bit represents a power of 2: 2 raised to the 0 power, 2 raised to the 1st power, and so on. To convert the binary number above, I added up the following values:

[View full width]

(128 * 1) + (64 * 0) + (32 * 1) + (16 * 0) + (8 * 1) + (4 * 0) + graphics/ccc.gif(2 * 1) + (1 * 1) = 171

By setting all of the bits to 1, you would get a value of 255, which is the maximum value of the Byte data type.

Just think of all the data you can store in a small amount of space by using a bitmap not the visual kind, but a string of bits where each on-off value represents something specific to your application. Consider this: If you need to store an on/off flag in your application and you use a character, it will take up two entire bytes of memory just to store the same type of on/off value as a bit! Just imagine how many bytes are wasted in an XML file, which contains hundreds of characters just to specify the format of the file.

The point is not to suggest that you try this one purpose for using a high-level language such as Visual Basic is to not have to worry about such low-level details but rather to give some perspective on storage space. Memory and disk space are cheap today, but you can easily appreciate the hard work of the early computer programmers and other bitheads who today continue to work with bit-level operations.

Converting Numbers Between Data Types

Visual Basic performs conversions implicitly and explicitly. Implicit conversions are automatic. For example, you could declare a variable of type Integer and assign the value 1.5 to it, which is not a valid integer value. Visual Basic would automatically convert the number using rounding and store 2 in the Integer variable. Explicit conversions are performed by calling conversion functions. As you will see throughout this chapter, the System.Convert class contains many static methods you can use to explicitly convert from one data type to another. Explicit conversion provides a higher degree of control over the conversion process and less chance for unexpected loss of data. You can force the use of only explicit conversions by setting the compiler's Option Strict setting to On. To do this, right-click your project's name in the Solution Explorer and choose Properties. Under the Build settings section, you set the Option Strict setting to On, as pictured in Figure 6.1.

Figure 6.1. Set Option Strict to On to enforce explicit conversions in your program.

graphics/06fig01.gif

Even when you set the Option Strict setting to On, certain types of conversions are still performed automatically, without having to call a conversion function.

Although every rule has exceptions, the general rule for automatic conversion of numbers is as follows:

If the data conversion does not result in a loss of data, the conversion is allowed. Otherwise, an error occurs.

To help explain conversions, Microsoft uses the terms widening and narrowing. Widening conversions are allowed, which means values can generally be moved from one type of variable to a wider type automatically, but not the reverse. In our previous example, you could store the Integer value of the USPopulation variable in the WorldPopulation variable using an assignment statement, but not the other way around. Conversions also are necessary when performing certain mathematical operations, because the result of a calculation may be of a wider type than the inputs.

The easiest way to convert numbers is by using the conversion methods provided by the Convert class. Figure 6.2 shows how the conversion methods are displayed in a pop-up menu if you type the variable name followed by a period.

Figure 6.2. Microsoft's Intellisense technology provides a list of methods in the Convert class, which can be used to convert variables from one type to another.

graphics/06fig02.gif

The following lines of code convert a decimal number to an integer and then back to a decimal:

 DecimalPrice = 19.95D  IntegerPrice = Convert.ToInt32(DecimalPrice)  DecimalPrice = IntegerPrice 

The previous code sample uses the ToInt32 function when converting the wider Decimal value to a value of type Integer. Note that the process of converting a decimal value to an integer value rounds off the fractional part of the number. Because the Integer data type cannot store the part to the right of the decimal point, that information is lost, even after converting the value back to a Decimal type. After the previous lines of code are executed, both the Integer and Decimal variables will contain the value 20.

Note

Visual Basic's Integer type is the equivalent of the .NET framework's Int32 type. Similarly, Short is Int16 and Long is Int64.


Formatting Numbers for Display

To convert a number to a string for displaying it on the screen, you can simply use the ToString method, as in the following line of code:

 TextBox1.Text = SalesTotal.ToString 

However, when writing down a number in real life, people often format the number to suit their needs. For example, adding commas, currency symbols, and other notations make the number more readable for others. Similarly, when you need to display a number on the screen or print a report, you need to make it as easy for others to visually comprehend.

Note

The ToString method of numeric data types will accept formatting codes, as in the following example:

 Messagebox.Show(DecimalPrice.ToString("C")) 


The Format function is a single function that can handle formatting of dates, numbers, and strings. It accepts a value and a control string, which can represent either a user-defined or named (system-defined) format. The following examples show how the format function can be used to format a monetary amount:

 Debug.WriteLine(Format(DecimalPrice, "C"))  Debug.WriteLine(Format(DecimalPrice, "$#,###.00")) 

The first line of the previous code uses a named format, C, which stands for Currency. Format specifiers are enclosed in double quotation marks. Table 6.3 shows some examples of the predefined formats for numbers.

Table 6.3. Named Formats to Make Displaying Numbers Easy

Format Description

Format String

Sample Input

Output

Currency Prints the number with a thousands separator and two digits after the decimal point.

C

1234.56

$1,234.56

Percent Multiples the number by 100 anddisplays the number followed by the percent sign.

P

0.0123

1.23%

Fixed Prints at least 1 digit to the left of the decimal and two digits to the right of the decimal.

F

1.55555

1.56

General No special formatting.

G

.567

0.567

Hexi Works with whole numbers only.

X

1234

4D2

Scientific Displays the number in scientific notation.

E

0.0123

1.230000E-002

Standard Prints the number with the thousands separator, and prints at least one digit to the left and two digits to the right of the decimal point.

N

1234

1,234.00

Note

For a complete list of available number formats, see the help topic "Predefined Numeric Formats."


If the named formats in Visual Basic don't meet your needs, you can define your own formats. You specify a format by indicating where the digits of the number should be placed, if thousands and decimal separators are used, and by listing any special characters that you want printed. For example, the following line of code displays a number with four decimal places and a thousands separator:

 MessageBox.Show(TotalDistance, "##,##0.0000") 

The codes you can use in specifying the format are defined in Table 6.4.

Table 6.4. Codes for Defining Numeric Formats

Symbol

Purpose

Meaning

0

Digit placeholder

Displays the digit or displays 0 if no digit appears in that location.

#

Digit placeholder

Displays the digit or displays nothing if no digit appears in that location. This causes leading and trailing zeros to be omitted.

.

Decimal separator

Indicates where the decimal point is displayed.

,

Thousands separator

Indicates where the separators are displayed.

%

Percentage indicator

Indicates where a percent sign is displayed. Also causes the number to be multiplied by 100.

E-, E+, e-, e+

Scientific Notation

Using E- or e- displays a minus sign next to negative exponents but displays no sign for positive exponents. Using E+ or e+ displays a sign for any exponent.

You should be aware that the named formats, as well as the ToString conversion methods, are culture-aware. This means they will be affected by the regional and culture settings of the system on which the program is running. For more information on regional formatting, see the later section entitled "Understanding Regional Settings."


    Team-Fly    
    Top
     



    Special Edition Using Visual Basic. NET
    Special Edition Using Visual Basic.NET
    ISBN: 078972572X
    EAN: 2147483647
    Year: 2001
    Pages: 198

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