Introduction to Variables
Introduction to Variables
Fundamentals of Variables
Introduction to Values
A value is a piece of information (called data) you need to use in your program. One way to use a value is to display it to the user. To do this, you can include the value in the parentheses of Console.Write(). Here is an example:
Imports System
Console.Write(248)
When using Console.Write(), an alternative is that, in the top section of the document, type Imports System.Console. After doing that, in your code, you can omit using Console.. Here is an example:
Imports System.Console Write(248)
Practical Learning: Introducing Variables
Imports System.Console
Module Program
Sub Main()
WriteLine("Hello World!")
End Sub
End Module
Introduction to Variables
A variable is a value that is stored in the computer memory (the random access memory, also called RAM). Such a value can be retrieved from the computer memory and displayed to the user.
Declaring a Variable
Before using a variable in your application, you must let the compiler know. Letting the compiler know is referred to as declaring a variable.
To declare a variable, you must provide at least two pieces of information. Actually, you have various options. We will start with one of them. One option to declare a variable is to type Dim, a space, and a name for the variable. The formula to follow is:
Dim variable-name
Initializing a Variable
When declaring a variable, you can give it a primary value. This is referred to as initializing the variable. You can use the following formula:
Dim variable-name = value
There are rules you should, and usually must, follow when naming your variables. The rules to follow are:
A name cannot be one of the words reserved for the Visual Basic language's own use. These words are also called keywords. Therefore, avoid using the following words to name a variable (this list includes official Visual Basic language keywords and words or expressions you should avoid):
| AddHandler | AddressOf | Alias | And | AndAlso |
| Ansi | As | Assembly | Auto | Boolean |
| ByRef | Byte | ByVal | Call | Case |
| Catch | CBool | CByte | CChar | CDate |
| CDbl | CDec | Char | CInt | Class |
| CLng | CObj | Compare | Const | Continue |
| CSByte | CShort | CSng | CStr | CType |
| CUInt | CULng | CUShort | Custom | Date |
| Decimal | Declare | Default | Delegate | Dim |
| DirectCast | Distinct | Do | Double | Each |
| Else | ElseIf | |||
| End | EndIf | Enum | Equals | Erase |
| Error | Event | Exit | Explicit | False |
| Finally | For | Friend | From | Function |
| Get | GetType | GetXmlNamespace | GoSub | GoTo |
| Group By | Group Join | Handles | If | Implements |
| Imports | In | Inherits | Integer | Interface |
| Into | Is | IsFalse | IsNot | IsTrue |
| Join | Key | Let | Lib | Like |
| Long | Loop | Me | Mid | Mod |
| Module | MustInherit | MustOverride | MyBase | MyClass |
| Namespace | Narrowing | New | Next | Not |
| Nothing | NotInheritable | NotOverridable | Object | Of |
| Off | On | Operator | Option | Optional |
| Or | Order By | OrElse | Overloads | Overridable |
| Overrides | ParamArray | Partial | Preserve | Private |
| Property | Protected | Public | RaiseEvent | ReadOnly |
| ReDim | REM | RemoveHandler | Resume | Return |
| SByte | Select | Set | Shadows | Shared |
| Short | Single | Skip | Skip While | Static |
| Step | Stop | Strict | String | Structure |
| Sub | SyncLock | Take | Take While | Text |
| Then | Throw | To | True | Try |
| TryCast | TypeOf | UInteger | ULong | Unicode |
| UShort | Until | Using | Variant | |
| Went | When | Where | While | Widening |
| With | WithEvents | WriteOnly | Xor |
Although you must always avoid using keywords as names of your variables in your program, if you insist on using one of these keywords to name something, put the word between square brackets. An example would be [True]
The Visual Basic language is not case sensitive. This means that NAME, name, and Name represent the same word. This means that, in the same section (normally called scope), you cannot have two variables with the same name that differ only by their cases. This would cause a name conflict. If you declare a variable in a scope and use it later with a different case, as long as the same characters are used on both names, the Visual Basic compiler would know what variable you are referring to and there would not be any conflict.
You should always make sure that you declare a variable before using it. Otherwise you may use two variables that seem to be different but because of a mistype, you would think that you are using two variables. Examples are Type and Tape.
To indicate to the compiler that each variable must be declared prior to being used, in the top section of your source file, you should type:
Option Explicit On
Values Fundamentals
Introduction
Besides the name, the second piece of information the compiler needs is the amount, also called size, of memory that the variable would need. This is because different values use different amounts of space.
The amount of space that a variable can occupy is referred to as its data type. The compiler uses categories of data types. For example, it can decide that a simple number would use one small "box" to store its value. On the other hand, it may decide that it would need ten "buckets" to store the title of a movie.
When you create a program, you can let the compiler know the amount of memory you would need for a particular variable. You can do this by specifying the most appropriate category. After telling the compiler that this particular variable would be used to store a number, you can change it in the middle of the program.
To reduce the number of mistakes that could be due to a possible wrong value being stored in a variable, the Visual Basic compiler uses two mechanisms: variable initialization and conversion.
A Review of Variable Declaration
We saw that, to declare a variable, you use the Dim keyword, followed by a name. Here is an example:
Module Exercise
Sub Main()
Dim Something
End Sub
End Module
After declaring a variable like this, the compiler reserves a portion of the computer memory for that variable but there may be two possible (small) problems: the compiler does not know how much space that variable would need to store its values and, because of this, the compiler would leave empty that area of memory.
To access the value of a variable, you can simply refer to its name. For example, you can display it to the user. To display a value, you can put the value in the parentheses of Console.WriteLine(). Here is an example:
Module Exercise
Sub Main()
Dim Something
Something = 25
Console.WriteLine(Something)
End Sub
End Module
Practical Learning: Declaring Variables
Module Training
Sub Main()
Dim CustomerName
Dim AccountNumber
Dim InitialDeposit
End Sub
End ModuleValue Conversion
We mentioned that you could declare a variable but not specify the type of value that would be stored in the memory area reserved for it. When you have declared a variable, the compiler gives it an initial value. This is referred to as initializing the variable. Instead of the compiler doing it, you too can initialize a variable. Initialization partially solves the two problems we mentioned.
In reality, when you declare a variable, the compiler primarily considers it a string and reserves enough space to store any amount of characters. One way you can solve this confusion is to initialize the variable.
To initialize a variable, type its name, followed by =, and followed by the desired value. Here is an example:
Module Exercise
Sub Main()
Dim Something
Something = 25
End Sub
End Module
After initializing the variable, the new value is stored in its reserved area of memory. When you initialize a variable, the compiler uses the given value to convert it to the appropriate type. For example, if you consider a variable with 25, it becomes considered an integral variable; that is, a variable whose memory can hold natural numbers.
We mentioned that, after declaring a variable, you could change its value whenever you judge it necessary. After declaring a variable as done in the above example, you can assign it any value of you choice. Here are examples:
Module Exercise
Sub Main()
Dim Something
Something = 25
Console.WriteLine(Something)
Something = "I need to submit my time sheet."
Console.WriteLine(Something)
Something = 237565.408
Console.WriteLine(Something)
End Sub
End Module
This is one of the unique features that make the Visual Basic (2005) language so flexible.
Requesting a Value
While many programs are meant to simply present values to the user, most applications are used to request values from the user. To make this possible and easy, we will write Console.ReadLine(). To use it, type it. Leave its parentheses empty.
When requesting a value, you should (must) indicate to the user the value you are requesting. To do that, before writing Console.ReadLine(), type Console.Write() on the previous line. In the parentheses of Console.Write(), type some text. That text should be clear so the user would know what you want. On the line that has Console.ReadLine(), first type a variable, followed by =, followed by Console.ReadLine(). Here is an example:
Console.Write("Enter your first name: ")
Dim FirstName = Console.ReadLine()
In future lessons, we will found out what Console.WriteLine(), Console.Write(), and Console.ReadLine() meant and what they do.
Primary Visual Basic Operations
Introduction
An operation is an action performed on one or more values either to modify one value or to produce a new value by combining existing values. Therefore, an operation is performed using at least one symbol and one value. The symbol used in an operation is called an operator. A variable or a value involved in an operation is called an operand.
A unary operator is an operator that performs its operation on only one operand.
An operator is referred to as binary if it operates on two operands.
The Line Continuation Operator: _
If you plan to write a long piece of code, to make it easier to read, you may need to divide it in various lines. You can do it as you would in any text editor. Here is an example:
Module Exercise
Sub Main()
Dim Something
Something =
"I need to submit my time sheet."
Console.WriteLine(Something)
End Sub
End Module
Notice that the variable Something and Manchester ... are written on different lines. As an alternative, you can use the line continuation operator represented by a white space followed by an underscore and an empty space. Here is an example:
Module Exercise
Sub Main()
Dim Something
Something = _
"I need to submit my time sheet."
Console.WriteLine(Something)
End Sub
End Module
A Primary Introduction to Strings
Introduction
A string is one or a group of symbols, readable or not. The symbols can be letters (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, and Z), digits (0, 1, 2, 3, 4, 5, 6, 7, 8, and 9) are non-readable characters (` ~ ! @ # $ % ^ & * ( ) - _ = + [ { ] } \ | ; : ' < ? . / , > "). To create a string, include its symbol, symbols, or combination inside double-quotes.
One way to use a string in a program is to store that string in the computer memory. To do that, you can declare a variable, specify its value in double-quotes and assign that value to the variable. Here is an example:
Dim firstName = "James"
Displaying a String
Displaying a value consists of printing it to the computer screen. If you simply have a string to display, include that string in the parentheses of Write(). Here is an example:
Imports System.Console
Module Program
Sub Main()
Write("Welcome to the World of Visual Basic Programming.")
End Sub
End Module
This would produce:
Welcome to the World of Visual Basic Programming.Press any key to close this window . . .
Primary Topics on Strings
If you use Write(), everything displays on the same line. This means that, after a string has displayed, the caret stays on the same line. As an alternative, you can display a string on one line and then move the caret on the next line. To do this, use WriteLine(). In this case, after the string is displayed, whatever item comes next would display in the next line. Just as you can include a value in the parentheses of Write(), you can put a value in the parentheses of WriteLine(). Consider the following example:
Imports System.Console
Module Program
Sub Main()
WriteLine("Welcome to the World of Visual Basic Programming!")
End Sub
End Module
This would produce:
Welcome to the World of Visual Basic Programming! Press any key to close this window . . .
In the same way, you can use any combination of Write() or of WriteLine() in your code. Here are examples:
Imports System.Console
Module Program
Sub Main()
Write("Country Name:")
Write(" ")
WriteLine("Australia")
End Sub
End Module
This would produce:
Country Name: Australia Press any key to close this window . . .
You can leave the parentheses of WriteLine() empty or include something in it but you can never leave the parentheses of Write() empty.
Practical Learning: Creating a New Line
Imports System.Console
Module Program
Sub Main()
WriteLine("-/-Georgetown Cleaning Services -/-")
WriteLine("===================================")
End Sub
End Module-/-Georgetown Cleaning Services -/- =================================== Press any key to close this window . . .
Imports System.Console
Module Program
Sub Main()
dim customerName = "James Burreck"
dim homePhone = "(202) 301-7030"
WriteLine("-/-Georgetown Cleaning Services -/-")
WriteLine("===================================")
Write("Customer: ")
WriteLine(customerName)
Write("Home Phone: ")
WriteLine(homePhone)
WriteLine("===================================")
End Sub
End Module-/-Georgetown Cleaning Services -/- =================================== Customer: James Burreck Home Phone: (202) 301-7030 =================================== Press any key to close this window . . .
Ordering Value Display
Imagine you have a certain value stored in a variable and you want to display the value of that variable on the screen. We already know that you can type Write() or WriteLine() and you can include a string in those parentheses. You can create an expression that includes the string in those parentheses and the value(s) of your choice. To proceed, the string in Write() or WriteLine() must be divided in two parts separated by a comma. The left side of the comma is the whole string you want to display. The right side of the comma is the name of a variable or a list of variables. If you use a list of variables (on the right side of the commas), the variables must be separated by commas. In the left string, type some curly brackets, {}, for each variable that is on the right side of the comma. The {} combination is called a placeholder. If you are displaying only one variable, include 0 in the {} placeholder. If you are displaying more than one variable, the numbers in the {} placeholders must be cumulative, as {0}, {1}, {2}, etc. The formulas to follow are:
Write("Something {0}", value)
Write("Something {0} {1}", value1, value2)
Write("Something {0} {1} {2}", value1, value2, value3)
Write("Something {0} {1} {2} {3}", value1, value2, value3, value4)
WriteLine("Something {0}", value)
WriteLine("Something {0} {1}", value1, value2)
WriteLine("Something {0} {1} {2}", value1, value2, value3)
WriteLine("Something {0} {1} {2} {3}", value1, value2, value3, value4)
String Interpolation
String interpolation consists of inserting one string in another existing string to get a new string. To perform this operation, start the existing string with the $ sign. In the existing string, include the curly bracjets placeholder {}. In the {} placeholder, include the desired string. Normally, you usually perform this operation for a string variable. Here is an example:
Imports System.Console
Module Program
Sub Main()
Dim firstName = "Robert"
WriteLine($"First Name: {firstName}")
WriteLine("===================================")
End Sub
End Module
This would produce:
First Name: Robert =================================== Press any key to close this window . . .
If you want to interpolate more strings, create as many {} sections as you want. In each {} placeholder, include the variable of your choice. Here is an example:
Imports System.Console
Module Program
Sub Main()
Dim firstName = "Robert"
Dim lastName = "Ellis"
WriteLine($"Customer: {firstName} {lastName}")
WriteLine("===================================")
End Sub
End Module
This would produce:
Customer: Robert Ellis =================================== Press any key to close this window . . .
The Width to Display a Value
The {} placeholder is primarily used to hold a value. One way to control the display of the value is to specify how wide an area must be reserved for the value. To specify this information, on the right side of the value in the placeholder, type a comma and a number for the desired width. Such a value is aligned to the right side of the reserved area. If you want the value to be aligned to the left, provide the value as a negative. Here are examples:
Imports System.Console
Module Program
Sub Main()
Dim firstName = "Robert"
Dim mi = "T"
Dim lastName = "Ellis"
WriteLine("First Name: {0,10}", firstName)
WriteLine("Middle: {0,10}", mi)
WriteLine("Last Name: {0,10}", lastName)
WriteLine("-----------------------------------")
WriteLine("First Name: {0,-10}", firstName)
WriteLine("Middle: {0,-10}", mi)
WriteLine("Last Name: {0,-10}", lastName)
WriteLine("===================================")
WriteLine($"First Name: {firstName}")
WriteLine($"First Name: {firstName}")
WriteLine($"First Name: {firstName,20}")
WriteLine($"First Name: {firstName,-20}")
End Sub
End Module
This would produce:
First Name: Robert Middle: T Last Name: Ellis ----------------------------------- First Name: Robert Middle: T Last Name: Ellis =================================== First Name: Robert First Name: Robert First Name: Robert First Name: Robert Press any key to close this window . . .
Requesting a String
To request a value from a user, write ReadLine(). When the program executes, the carret would blink to the user to type something. To indicate what the user is supposed to type, you can precede ReadLine() with a string in Write() or WriteLine().
When the user has typed something in response to ReadLine(), you can get that value and store it in a variable. To do that, assign ReadLine() to a string. You can then use that variable normally. In the same way, you can use ReadLine() as many times as you want.
Introduction to Natural Numbers
Overview
A natural number is a value that contains only digits. To recognize such values, the Visual Basic language provides a data type named Integer. To declare a variable that would hold a natural number, you can simply declare the variable using the Dim keyword and a name for the variable. Here is an example:
Dim age
The Value of an Integral Variable
To specify the variable of an Integer type, provide a value that contains only digits. Here is an example:
Dim age = 15
Displaying an Integral Value
To display a number to the user, you can include that number in the parentheses of Write() or WriteLine(). Here is an example:
Imports System.Console
Module Program
Sub Main()
WriteLine(9285)
End Sub
End Module
This would produce:
9285 Press any key to close this window . . .
If the value is stored in a variable, you can display that value to the user. To do that, you can type the name of the variable in the parentheses of Write() or WriteLine(). Here is an example:
Imports System.Console
Module Program
Sub Main()
Dim monthlySalary = 3288
Write("Monthly Salary: ")
WriteLine(monthlySalary)
End Sub
End Module
This would produce:
Monthly Salary: 3288 Press any key to close this window . . .
You can also use string interpolatione to display the value of an integral variable. To do this, as seen with strings, start the interior of the parentheses of Write() or WriteLine() with $ followed by double-quotes. In the double-quote, write {}. In those square brackets, include the name of the integral variable.
Creating a Large Integer
The value of an integer can be between -2147483648 and 2147484647 (or -2,147,483,648 and 2,147,484,647). If you need to use a large value, to make it easier to humanly read, you can separate the thousands by underscores. Here are examples:
Imports System.Console
Module Program
Sub Main()
Dim areaOfChina = 9_596_961
Dim areaOfCanada = 9_984_670
Dim areaOfBurkinaFaso = 275_200
Dim areaOfDjibouti = 23_200
WriteLine("Countries Areas")
WriteLine("---------------------")
Write("Djibouti: ")
WriteLine(areaOfDjibouti)
Write("Burkina Faso: ")
WriteLine(areaOfBurkinaFaso)
Write("China: ")
WriteLine(areaOfChina)
Write("Canada: ")
WriteLine(areaOfCanada)
End Sub
End Module
This would produce:
Countries Areas --------------------- Djibouti: 23200 Burkina Faso: 275200 China: 9596961 Canada: 9984670 Press any key to close this window . . .
Practical Learning: Introducing Integers
Imports System.Console
Module Program
Sub Main()
Dim customerName = "James Burreck"
Dim homePhone = "(202) 301-7030"
Dim numberOfShirts = 1
Dim numberOfPants = 1
Dim numberOfDresses = 1
Dim orderMonth = 3
Dim orderDay = 15
Dim orderYear = 2020
WriteLine("-/-Georgetown Cleaning Services -/-")
WriteLine("===================================")
Write("Customer: ")
WriteLine(customerName)
Write("Home Phone: ")
WriteLine(homePhone)
Write("Order Date: ")
Write(orderMonth)
Write("/")
Write(orderDay)
Write("/")
WriteLine(orderYear)
WriteLine("-----------------------------------")
WriteLine("Item Type Qty")
WriteLine("-----------------------------------")
Write("Shirts ")
WriteLine(numberOfShirts)
Write("Pants ")
WriteLine(numberOfPants)
Write("Dresses ")
WriteLine(numberOfDresses)
WriteLine("===================================")
End Sub
End Module-/-Georgetown Cleaning Services -/- =================================== Customer: James Burreck Home Phone: (202) 301-7030 Order Date: 3/15/2020 ----------------------------------- Item Type Qty ----------------------------------- Shirts 1 Pants 1 Dresses 1 =================================== Press any key to close this window . . .
Converting a Value to an Integer
Your programs will deal with various types of values. Some of those values must be involved in arithmetic operations; but sometimes, when you have a value, you don't know what type that value is. Normally, beformed involving a value in a number-based operation, you may have to first convert that value to a number. You have many options. As one way to convert a value to an integer, type CInt(). In the parentheses of CInt(), type the value to be converted. Here is an example:
Imports System.Console
Module Program
Sub Main()
Write("Enter a number: ")
Dim request = ReadLine()
Dim Number = CInt(request)
Write("Number: ")
WriteLine(Number)
WriteLine("===================================")
End Sub
End Module
The above technique, which consists of using CInt(), if an effective solution that is part of the Visual Basic language's own library. As an alternative, the .NET Framework provides its own solution. To use it, that is, to convert a value to an integer, type Integer.Parse(). In the parentheses of Integer.Parse(), type the value to be converted. Here is an example:
Imports System.Console
Module Program
Sub Main()
Write("Enter a number: ")
Dim request = ReadLine()
Dim Number = Integer.Parse(request)
Write("Number: ")
WriteLine(Number)
WriteLine("===================================")
End Sub
End Module
Requesting an Integral Value
We already saw that, to request a value, you can use ReadLine(), but ReadLine() gets a string. As a result, you must convert the value of ReadLine() to an integer. To do that, ou can first get the value, then convert it. This can be done in two steps as follows:
Imports System.Console
Module Program
Sub Main()
Write("Enter a number: ")
Dim request = ReadLine()
Dim number = CInt(request)
WriteLine(number)
WriteLine("===================================")
End Sub
End Module
To reduce the number of lines of your code, you can include ReadLine() in the parentheses of CInt() or Integer.Parse().
Introduction to Floating-Point Numbers
A floating-point number is a number made of either only digits or two parts separated by a symbol referred to as a decimal separator. As one way to support floating-point numbers, the Visual Basic language provides a data type named Double. Use it to declare a variable for a number. To provide a value for the variable, you can use the same types of numbers we saw for integers. Here are examples:
Imports System.Console
Module Program
Sub Main()
Dim areaMaine = 35385
Dim areaAlaska = 1_723_337
WriteLine("States Areas")
WriteLine("------------------")
Write("Maine: ")
WriteLine(areaMaine)
Write("Alaska: ")
WriteLine(areaAlaska)
WriteLine("==================")
End Sub
End Module
This would produce:
States Areas ------------------ Maine: 35385 Alaska: 1723337 ================== Press any key to close this window . . .
A Floating-Point Number with Precision
The primary difference between an integer and a floating-point number is that a decimal number can include a second part referred to as a precision. To specify the precision of a number, after the natural part, add the symbol used as the decimal separator. In US English, this is the period. Here is an example:
Imports System.Console
Module Program
Sub Main()
Dim hourlySalary = 25.85
Write("Hourly Salary: ")
WriteLine(hourlySalary)
End Sub
End Module
This would produce:
Hourly Salary: 25.85 Press any key to close this window . . .
If the integral part is large, you can use it "as is" or you can separate its thousansds with underscores. Here are examples:
Imports System.Console
Module Program
Sub Main()
Dim areaGuam = 570.62
Dim areaAlaska = 665_384.04
Dim areaSouthDakota = 77115.68
Dim areaTennessee = 42_144.25
WriteLine("States Areas")
WriteLine("=======================")
WriteLine("Guam: {0}", areaGuam)
WriteLine("Alaska: {0}", areaAlaska)
WriteLine("Tennessee: {0}", areaTennessee)
WriteLine("South Dakota: {0}", areaSouthDakota)
End Sub
End Module;
This would produce:
States Areas ======================= Guam: 570.62 Alaska: 665384.04 Tennessee: 42144.25 South Dakota: 77115.68 Press any key to close this window . . .
In the above examples, we used the underscore separator only on the integral part of the number. In reality, you can also use that separator in the precision side. Here are examples:
Imports System.Console
Module Program
Sub Main()
Dim number = 085.24_497
Dim value = 947_596.75_038
WriteLine("Number: {0}", number)
WriteLine("Value: {0}", value)
WriteLine("=====================")
End Sub
End Module
This would produce:
Number: 85.24497 Value: 947596.75038 ==================== Press any key to close this window . . .
Converting a Value to Double-Precision
To convert a value to a floating-point number with double-precision, you have many options. As one solution, type CDbl(). In the parentheses of CDbl(), type the value to be converted. Here is an example:
Imports System.Console
Module Program
Sub Main()
Dim value = "495.86"
Dim number = CDbl(value)
WriteLine(number)
WriteLine("=====================")
End Sub
End Module
This would produce:
495.86 ===================== Press any key to close this window . . .
CDbl() is a technique available in the Visual Basic language. As an alternative, the .NET Framework provides another solution. Based on it, to convert a value to a decimal, type Double.Parse(). In the parentheses of Double.Parse(), type the value to be converted. Here is an example:
Imports System.Console
Module Program
Sub Main()
Dim value = "495.86"
Dim number = Double.Parse(value)
WriteLine(number)
WriteLine("=====================")
End Sub
End Module
Requesting a Decimal Number
We saw that, to request a value, you can use ReadLine(). Here is an example:
Imports System.Console
Module Program
Sub Main()
Write("Enter a number: ")
Dim request = ReadLine()
End Sub
End Module
Once you have the value, you must convert it to a Double value. We saw that you can use either CDbl() or Double.Parse() to do that. Here is an example:
Imports System.Console
Module Program
Sub Main()
Write("Enter a number: ")
Dim request = ReadLine()
Dim number = CDbl(request)
WriteLine(number)
WriteLine("===================================")
End Sub
End Module
You can also include ReadLine() in the parentheses of CDbl() or Double.Parse().
Displaying a Decimal Number
Introduction
So far, to display the value of a decimal variable, we simply typed it in the parentheses of Write() or WriteLine() as we saw with strings (and integers). You can also use string interpolation to display the value. Here are examples:
Imports System.Console
Module Program
Sub Main()
Dim number = 285.24_497
Dim value = 947_596.75_038
WriteLine($"Number: {number}")
WriteLine($"Value: {value}")
WriteLine("===================================")
End Sub
End Module
This would produce:
Number: 285.24497 Value: 947596.75038 =================================== Press any key to close this window . . .
Displaying a Number with Fixed Precision
Because floating-point numbers use a precision part, sometimes you want to control how the number displays. The string interpolation mechanism provides many options. To start, in the {} placeholder, after the name of the variable, type a colon (:). After the colon, if you want to display the number with two decimal places, type f or F, n. Here are examples:
Imports System.Console
Module Program
Sub Main()
Dim nbr = 4848075.5279
Dim val = 63828493.806
Dim number = 28835.24_497
Dim value = 947_596.75_038
WriteLine($"Number: {nbr:f}")
WriteLine($"Value: {val:f}")
WriteLine($"Number: {number:F}")
WriteLine($"Value: {value:F}")
WriteLine("===================================")
End Sub
End Module
This would produce:
Number: 4848075.53 Value: 63828493.81 Number: 28835.24 Value: 947596.75 =================================== Press any key to close this window . . .
Formatting the Number with Thousands Separators
If the integral part of the number is large and you want to display it with decimal separators in the integral part but two decimal places, in the {} placeholder of the string interpolation, after the colon (:), type n or N. Here are examples:
Imports System.Console
Module Program
Sub Main()
Dim nbr = 484.5279
Dim val = 63.806828493
Dim number = 288358075.24_497
Dim value = 947_596.75_038
WriteLine($"Number: {nbr:n}")
WriteLine($"Value: {val:n}")
WriteLine($"Number: {number:N}")
WriteLine($"Value: {value:N}")
WriteLine("===================================")
End Sub
End Module
This would produce:
Number: 484.53 Value: 63.81 Number: 288,358,075.24 Value: 947,596.75 =================================== Press any key to close this window . . .
Practical Learning: Introducing Double-Precision Numbers
Imports System.Console
Module Program
Sub Main()
Dim customerName = "James Burreck"
dim homePhone = "(202) 301-7030"
dim numberOfShirts = 1
dim numberOfPants = 1
dim numberOfDresses = 1
dim priceOneShirt = 0.95
dim priceAPairOfPants = 2.95
dim priceOneDress = 4.55
dim orderMonth = 3
dim orderDay = 15
dim orderYear = 2020
WriteLine("-/-Georgetown Cleaning Services -/-")
WriteLine("===================================")
WriteLine("Customer: {0}", customerName)
WriteLine("Home Phone: {0}", homePhone)
WriteLine("Order Date: {0}/{1}/{2}", orderMonth, orderDay, orderYear)
WriteLine("-----------------------------------")
WriteLine("Item Type Qty Sub-Total")
WriteLine("------------------------")
Write("Shirts ")
Write(numberOfShirts)
Write(" ")
WriteLine(priceOneShirt)
Write("Pants ")
Write(numberOfPants)
Write(" ")
WriteLine(priceAPairOfPants)
Write("Dresses ")
Write(numberOfDresses)
Write(" ")
WriteLine(priceOneDress)
WriteLine("===================================")
End Sub
End Module-/-Georgetown Cleaning Services -/- =================================== Customer: James Burreck Home Phone: (202) 301-7030 Order Date: 3/15/2020 ----------------------------------- Item Type Qty ----------------------------------- Shirts 1 Pants 1 Dresses 1 =================================== Press any key to close this window . . .
|
|
|||
| Previous | Copyright © 2008-2026, FunctionX | Tueday 15 August 2024 | Next |
|
|
|||