SlideShare a Scribd company logo
1 of 35
Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 1
Chapter 4
How to work with
numeric and string data
Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 2
The built-in value types
C# .NET
keyword Bytes type Description
byte 1 Byte Positive integer value from 0 to 255
sbyte 1 SByte Signed integer value from -128 to 127
short 2 Int16 Integer from –32,768 to +32,767
ushort 2 UInt16 Unsigned integer from 0 to 65,535
int 4 Int32 Integer from –2,147,483,648 to
+2,147,483,647
uint 4 UInt32 Unsigned integer from 0 to
4,294,967,295
long 8 Int64 Integer from
–9,223,372,036,854,775,808 to
+9,223,372,036,854,775,807
Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 3
The built-in value types (continued)
C# .NET
keyword Bytes type Description
ulong 8 UInt64 Unsigned integer from 0 to
+18,446,744,073,709,551,615
float 4 Single Non-integer number with
approximately 7 significant digits
double 8 Double Non-integer number with
approximately 14 significant digits
decimal 16 Decimal Non-integer number with up to 28
significant digits (integer and
fraction) that can represent values up
to 79,228 x 1024
char 2 Char A single Unicode character
bool 1 Boolean A true or false value
Slide 4
The built-in value types (continued)
• The integer data types can be used to store signed and unsigned
whole numbers of various sizes.
• Since the decimal type is the most accurate non-integer data type,
it’s typically used to store monetary values.
Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 5
How to declare and initialize a variable in two
statements
Syntax
type variableName;
variableName = value;
Example
int counter; // declaration statement
counter = 1; // assignment statement
Definition
• A variable stores a value that can change as a program executes.
Naming conventions
• Start the names of variables with a lowercase letter, and capitalize
the first letter of each word after the first word. This is known as
camel notation.
Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 6
How to declare and initialize a variable in one
statement
Syntax
type variableName = value;
Examples
int counter = 1;
long numberOfBytes = 20000;
float interestRate = 8.125f;
// f or F indicates a float value
double price = 14.95;
decimal total = 24218.1928m;
// m or M indicates a decimal value
double starCount = 3.65e+9; // scientific notation
char letter = 'A';
// enclose a character value in single quotes
bool valid = false;
int x = 0, y = 0;
// initialize 2 variables with 1 statement
Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 7
How to declare and initialize a constant
Syntax
const type ConstantName = value;
Examples
const int DaysInNovember = 30;
const decimal SalesTax = .075m;
Definition
• A constant stores a value that can’t be changed.
Naming conventions
• Capitalize the first letter of each word of a constant name. This is
known as Pascal notation.
Slide 8
How to declare and initialize variables and
constants
• Before you can use a variable or constant, you must declare its
type and assign an initial value to it.
• To declare or initialize more than one variable for a single data
type in a single statement, use commas to separate the variable
names or assignments.
• To identify literal values as float values, you must type the letter f
or F after the number. To identify decimal values, you must type
the letter m or M after the number.
• The keywords for data types must be coded with all lowercase
letters.
Slide 9
Assignment operator
Operator Name Description
= Assignment Assigns a new value to the variable.
The syntax for a simple assignment statement
variableName = expression;
Typical assignment statements
counter = 7;
newCounter = counter;
discountAmount = subtotal * .2m;
total = subtotal – discountAmount;
Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 10
Statements that use the same variable on both
sides of the equals sign
total = total + 100m;
total = total – 100m;
price = price * .8m;
Statements that use the shortcut assignment
operators
total += 100m;
total -= 100m;
price *= .8m;
Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 11
Arithmetic operators
Operator Name Description
+ Addition Adds two operands.
- Subtraction Subtracts the right operand from
the left operand.
* Multiplication Multiplies the right operand and the
left operand.
/ Division Divides the right operand into the
left operand. If both operands are
integers, then the result is an
integer.
% Modulus Returns the value that is left over
after dividing the right operand into
the left operand.
Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 12
Arithmetic operators (continued)
Operator Name Description
+ Positive sign Returns the value of the operand.
- Negative sign Changes a positive value to
negative, and vice versa.
++ Increment Adds 1 to the operand (x = x + 1).
-- Decrement Subtracts 1 from the operand
(x = x - 1).
Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 13
Arithmetic expressions that use integers
int x = 14;
int y = 8;
int result1 = x + y; // result1 = 22
int result2 = x - y; // result2 = 6
int result3 = x * y; // result3 = 112
int result4 = x / y; // result4 = 1
int result5 = x % y; // result5 = 6
int result6 = -y + x; // result6 = 6
int result7 = --y; // result7 = 7
int result8 = ++x; // result8 = 15, x = 15
Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 14
Arithmetic expressions that use decimal values
decimal a = 8.5m;
decimal b = 3.4m;
decimal result11 = a + b; // result11 = 11.9
decimal result12 = a - b; // result12 = 5.1
decimal result13 = a / b; // result13 = 2.5
decimal result14 = a * b; // result14 = 28.90
decimal result15 = a % b; // result15 = 1.7
decimal result16 = -a; // result16 = -8.5
decimal result17 = --a; // result17 = 7.5
decimal result18 = ++b; // result18 = 4.4
Arithmetic expressions that use characters
char letter1 = 'C'; // letter1 = 'C'
// Unicode integer is 67
char letter2 = ++letter1; // letter2 = 'D'
// Unicode integer is 68
Slide 15
What is the value of the “a”?
decimal a = 2 + 3 * 4 + 5;
Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 16
The order of precedence for arithmetic operations
1. Increment and decrement
2. Positive and negative
3. Multiplication, division, and modulus
4. Addition and subtraction
Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 17
A calculation that uses the default order of
precedence
decimal discountPercent = .2m; // 20% discount
decimal price = 100m; // $100 price
price = price * 1 – discountPercent; // price = $99.8
A calculation that uses parentheses to specify the
order of precedence
decimal discountPercent = .2m; // 20% discount
decimal price = 100m; // $100 price
price = price * (1 – discountPercent); // price = $80
Examples that use prefixed and postfixed
increment and decrement operators
int a = 5;
int b = 5
int y = ++a; // a = 6, y = 6
int z = b++; // b = 6, z = 5
Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 18
Five static methods of the Math class
The syntax of the Round method
Math.Round(decimalNumber[, precision])
The syntax of the Pow method
Math.Pow(number, power)
The syntax of the Sqrt method
Math.Sqrt(number)
The syntax of the Min and Max methods
Math.{Min|Max}(number1, number2)
There are many, many more…
Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 19
Statements that use static methods of the Math
class
int shipWeight = Math.Round(shipWeightDouble);
// round to a whole number
double orderTotal = Math.Round(orderTotal, 2);
// round to 2 decimal places
double area = Math.Pow(radius, 2) * Math.PI;
// area of circle
double sqrtX = Math.Sqrt(x);
double maxSales = Math.Max(lastYearSales, thisYearSales);
int minQty = Math.Min(lastYearQty, thisYearQty);
Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 20
Results from static methods of the Math class
Statement Result
Math.Round(23.75) 24
Math.Round(23.5) 24
Math.Round(24.5) 24
Math.Round(23.754, 2) 23.75
Math.Round(23.755, 2) 23.76
Math.Pow(5, 2) 25
Math.Sqrt(20.25) 4.5
Math.Max(23.75, 20.25) 23.75
Math.Min(23.75, 20.25) 20.25
Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 21
How to declare and initialize a string
string message1 = "Invalid data entry.";
string message2 = "";
string message3 = null;
How to join strings
string firstName = "Bob"; // firstName is "Bob"
string lastName = "Smith"; // lastName is "Smith"
string name = firstName + " " + lastName;
// name is "Bob Smith"
How to join a string and a number
double price = 14.95;
string priceString = "Price: $" + price;
// priceString is "Price: $14.95"
Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 22
How to append one string to another string
string firstName = "Bob"; // firstName is "Bob"
string lastName = "Smith"; // lastName is "Smith"
string name = firstName + " "; // name is "Bob "
name = name + lastName; // name is "Bob Smith"
How to append one string to another with the +=
operator
string firstName = "Bob"; // firstName is "Bob"
string lastName = "Smith"; // lastName is "Smith"
string name = firstName + " "; // name is "Bob "
name += lastName; // name is "Bob Smith"
Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 23
Common methods for data conversion
Method Description
ToString([format]) A method that converts the value to its
equivalent string representation using the
specified format. If the format is omitted, the
value isn’t formatted.
Parse(string) A static method that converts the specified
string to an equivalent data value.
Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 24
Some of the static methods of the Convert class
Method Description
ToDecimal(value) Converts the value to the decimal data type.
ToDouble(value) Converts the value to the double data type.
ToInt32(value) Converts the value to the int data type.
ToChar(value) Converts the value to the char data type.
ToBool(value) Converts the value to the bool data type.
ToString(value) Converts the value to a string object.
Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 25
Statements that use ToString and Parse
decimal sales = 2574.98m;
string salesString = sales.ToString(); // decimal to string
sales = Decimal.Parse(salesString); // string to decimal
An implicit call of the ToString method
double price = 49.50;
string priceString = "Price: $" + price;
// automatic ToString call
Conversion statements that use the Convert class
decimal subtotal = Convert.ToDecimal(txtSubtotal.Text);
// string to decimal
int years = Convert.ToInt32(txtYears.Text); // string to int
txtSubtotal.Text = Convert.ToString(subtotal);
// decimal to string
int subtotalInt = Convert.ToInt32(subtotal);
// decimal to int
Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 26
Standard numeric formatting codes
Code Format
C or c Currency
P or p Percent
N or n Number
F or f Float
D or d Digits
E or e Exponential
G or g General
Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 27
How to use the ToString method to format a number
Statement Example
string monthlyAmount = amount.ToString("c"); $1,547.20
string interestRate = interest.ToString("p1"); 2.3%
string quantityString = quantity.ToString("n0"); 15,000
string paymentString = payment.ToString("f3"); 432.818
Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 28
How to use the Format method of the String class to
format a number
Statement Result
string monthlyAmount = String.Format("{0:c}", 1547.2m); $1,547.20
string interestRate = String.Format("{0:p1}", .023m); 2.3%
string quantityString = String.Format("{0:n0}", 15000); 15,000
string paymentString = String.Format("{0:f3}", 432.8175); 432.818
The syntax of the format specification used by the
Format method
{index:formatCode}
Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 29
The Invoice Total form
Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 30
The controls on the Invoice Total form that are
referred to in the code
Object type Name Description
TextBox txtSubtotal A text box that accepts a
subtotal amount
TextBox txtDiscountPercent A read-only text box that
displays the discount percent
TextBox txtDiscountAmount A read-only text box that
displays the discount amount
TextBox txtTotal A read-only text box that
displays the invoice total
Button btnCalculate Calculates the discount amount
and invoice total when clicked
Button btnExit Closes the form when clicked
Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 31
The event handlers for the Invoice Total form
private void btnCalculate_Click(object sender,
System.EventArgs e)
{
decimal subtotal = Convert.ToDecimal(txtSubtotal.Text);
decimal discountPercent = .25m;
decimal discountAmount = subtotal * discountPercent;
decimal invoiceTotal = subtotal - discountAmount;
txtDiscountPercent.Text
= discountPercent.ToString("p1");
txtDiscountAmount.Text = discountAmount.ToString("c");
txtTotal.Text = invoiceTotal.ToString("c");
txtSubtotal.Focus();
}
private void btnExit_Click(object sender,
System.EventArgs e)
{
this.Close();
}
Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 32
The enhanced Invoice Total form
Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 33
The code for the class variables and two event
handlers
int numberOfInvoices = 0;
decimal totalOfInvoices = 0m;
decimal invoiceAverage = 0m;
private void btnCalculate_Click(object sender, EventArgs e)
{
decimal subtotal
= Convert.ToDecimal(txtEnterSubtotal.Text);
decimal discountPercent = .25m;
decimal discountAmount
= Math.Round(subtotal * discountPercent, 2);
decimal invoiceTotal = subtotal - discountAmount;
txtSubtotal.Text = subtotal.ToString("c");
txtDiscountPercent.Text
= discountPercent.ToString("p1");
txtDiscountAmount.Text = discountAmount.ToString("c");
txtTotal.Text = invoiceTotal.ToString("c");
Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 34
The class variables and two event handlers (cont.)
numberOfInvoices++;
totalOfInvoices += invoiceTotal;
invoiceAverage = totalOfInvoices / numberOfInvoices;
txtNumberOfInvoices.Text = numberOfInvoices.ToString();
txtTotalOfInvoices.Text = totalOfInvoices.ToString("c");
txtInvoiceAverage.Text = invoiceAverage.ToString("c");
txtEnterSubtotal.Text = "";
txtEnterSubtotal.Focus();
}
Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 35
The class variables and two event handlers (cont.)
private void btnClearTotals_Click(object sender,
System.EventArgs e)
{
numberOfInvoices = 0;
totalOfInvoices = 0m;
invoiceAverage = 0m;
txtNumberOfInvoices.Text = "";
txtTotalOfInvoices.Text = "";
txtInvoiceAverage.Text = "";
txtEnterSubtotal.Focus();
}

More Related Content

What's hot

C# Tutorial MSM_Murach chapter-06-slides
C# Tutorial MSM_Murach chapter-06-slidesC# Tutorial MSM_Murach chapter-06-slides
C# Tutorial MSM_Murach chapter-06-slidesSami Mut
 
C# Tutorial MSM_Murach chapter-19-slides
C# Tutorial MSM_Murach chapter-19-slidesC# Tutorial MSM_Murach chapter-19-slides
C# Tutorial MSM_Murach chapter-19-slidesSami Mut
 
C# Tutorial MSM_Murach chapter-05-slides
C# Tutorial MSM_Murach chapter-05-slidesC# Tutorial MSM_Murach chapter-05-slides
C# Tutorial MSM_Murach chapter-05-slidesSami Mut
 
C# Tutorial MSM_Murach chapter-16-slides
C# Tutorial MSM_Murach chapter-16-slidesC# Tutorial MSM_Murach chapter-16-slides
C# Tutorial MSM_Murach chapter-16-slidesSami Mut
 
C# Tutorial MSM_Murach chapter-14-slides
C# Tutorial MSM_Murach chapter-14-slidesC# Tutorial MSM_Murach chapter-14-slides
C# Tutorial MSM_Murach chapter-14-slidesSami Mut
 
C# Tutorial MSM_Murach chapter-24-slides
C# Tutorial MSM_Murach chapter-24-slidesC# Tutorial MSM_Murach chapter-24-slides
C# Tutorial MSM_Murach chapter-24-slidesSami Mut
 
C# Tutorial MSM_Murach chapter-25-slides
C# Tutorial MSM_Murach chapter-25-slidesC# Tutorial MSM_Murach chapter-25-slides
C# Tutorial MSM_Murach chapter-25-slidesSami Mut
 
C# Tutorial MSM_Murach chapter-02-slides
C# Tutorial MSM_Murach chapter-02-slidesC# Tutorial MSM_Murach chapter-02-slides
C# Tutorial MSM_Murach chapter-02-slidesSami Mut
 
C# Tutorial MSM_Murach chapter-03-slides
C# Tutorial MSM_Murach chapter-03-slidesC# Tutorial MSM_Murach chapter-03-slides
C# Tutorial MSM_Murach chapter-03-slidesSami Mut
 
C# Tutorial MSM_Murach chapter-20-slides
C# Tutorial MSM_Murach chapter-20-slidesC# Tutorial MSM_Murach chapter-20-slides
C# Tutorial MSM_Murach chapter-20-slidesSami Mut
 
C# Tutorial MSM_Murach chapter-22-slides
C# Tutorial MSM_Murach chapter-22-slidesC# Tutorial MSM_Murach chapter-22-slides
C# Tutorial MSM_Murach chapter-22-slidesSami Mut
 
C# Tutorial MSM_Murach chapter-10-slides
C# Tutorial MSM_Murach chapter-10-slidesC# Tutorial MSM_Murach chapter-10-slides
C# Tutorial MSM_Murach chapter-10-slidesSami Mut
 
C# Tutorial MSM_Murach chapter-21-slides
C# Tutorial MSM_Murach chapter-21-slidesC# Tutorial MSM_Murach chapter-21-slides
C# Tutorial MSM_Murach chapter-21-slidesSami Mut
 
Programming with c language practical manual
Programming with c language practical manualProgramming with c language practical manual
Programming with c language practical manualAnil Bishnoi
 
Java Graphics
Java GraphicsJava Graphics
Java GraphicsShraddha
 
Bis 311 final examination answers
Bis 311 final examination answersBis 311 final examination answers
Bis 311 final examination answersRandalHoffman
 

What's hot (20)

C# Tutorial MSM_Murach chapter-06-slides
C# Tutorial MSM_Murach chapter-06-slidesC# Tutorial MSM_Murach chapter-06-slides
C# Tutorial MSM_Murach chapter-06-slides
 
C# Tutorial MSM_Murach chapter-19-slides
C# Tutorial MSM_Murach chapter-19-slidesC# Tutorial MSM_Murach chapter-19-slides
C# Tutorial MSM_Murach chapter-19-slides
 
C# Tutorial MSM_Murach chapter-05-slides
C# Tutorial MSM_Murach chapter-05-slidesC# Tutorial MSM_Murach chapter-05-slides
C# Tutorial MSM_Murach chapter-05-slides
 
C# Tutorial MSM_Murach chapter-16-slides
C# Tutorial MSM_Murach chapter-16-slidesC# Tutorial MSM_Murach chapter-16-slides
C# Tutorial MSM_Murach chapter-16-slides
 
C# Tutorial MSM_Murach chapter-14-slides
C# Tutorial MSM_Murach chapter-14-slidesC# Tutorial MSM_Murach chapter-14-slides
C# Tutorial MSM_Murach chapter-14-slides
 
C# Tutorial MSM_Murach chapter-24-slides
C# Tutorial MSM_Murach chapter-24-slidesC# Tutorial MSM_Murach chapter-24-slides
C# Tutorial MSM_Murach chapter-24-slides
 
C# Tutorial MSM_Murach chapter-25-slides
C# Tutorial MSM_Murach chapter-25-slidesC# Tutorial MSM_Murach chapter-25-slides
C# Tutorial MSM_Murach chapter-25-slides
 
C# Tutorial MSM_Murach chapter-02-slides
C# Tutorial MSM_Murach chapter-02-slidesC# Tutorial MSM_Murach chapter-02-slides
C# Tutorial MSM_Murach chapter-02-slides
 
C# Tutorial MSM_Murach chapter-03-slides
C# Tutorial MSM_Murach chapter-03-slidesC# Tutorial MSM_Murach chapter-03-slides
C# Tutorial MSM_Murach chapter-03-slides
 
C# Tutorial MSM_Murach chapter-20-slides
C# Tutorial MSM_Murach chapter-20-slidesC# Tutorial MSM_Murach chapter-20-slides
C# Tutorial MSM_Murach chapter-20-slides
 
C# Tutorial MSM_Murach chapter-22-slides
C# Tutorial MSM_Murach chapter-22-slidesC# Tutorial MSM_Murach chapter-22-slides
C# Tutorial MSM_Murach chapter-22-slides
 
C# Tutorial MSM_Murach chapter-10-slides
C# Tutorial MSM_Murach chapter-10-slidesC# Tutorial MSM_Murach chapter-10-slides
C# Tutorial MSM_Murach chapter-10-slides
 
C# Tutorial MSM_Murach chapter-21-slides
C# Tutorial MSM_Murach chapter-21-slidesC# Tutorial MSM_Murach chapter-21-slides
C# Tutorial MSM_Murach chapter-21-slides
 
Intake 38 9
Intake 38 9Intake 38 9
Intake 38 9
 
Intake 38 7
Intake 38 7Intake 38 7
Intake 38 7
 
Intake 38 8
Intake 38 8Intake 38 8
Intake 38 8
 
Oops Quiz
Oops QuizOops Quiz
Oops Quiz
 
Programming with c language practical manual
Programming with c language practical manualProgramming with c language practical manual
Programming with c language practical manual
 
Java Graphics
Java GraphicsJava Graphics
Java Graphics
 
Bis 311 final examination answers
Bis 311 final examination answersBis 311 final examination answers
Bis 311 final examination answers
 

Similar to C# Tutorial MSM_Murach chapter-04-slides

Similar to C# Tutorial MSM_Murach chapter-04-slides (20)

SECTION D2)Display the item number and total cost for each order l.docx
SECTION D2)Display the item number and total cost for each order l.docxSECTION D2)Display the item number and total cost for each order l.docx
SECTION D2)Display the item number and total cost for each order l.docx
 
Chapter1.pptx
Chapter1.pptxChapter1.pptx
Chapter1.pptx
 
C SLIDES PREPARED BY M V B REDDY
C SLIDES PREPARED BY  M V B REDDYC SLIDES PREPARED BY  M V B REDDY
C SLIDES PREPARED BY M V B REDDY
 
C Operators
C OperatorsC Operators
C Operators
 
Cs211 module 1_2015
Cs211 module 1_2015Cs211 module 1_2015
Cs211 module 1_2015
 
Cs211 module 1_2015
Cs211 module 1_2015Cs211 module 1_2015
Cs211 module 1_2015
 
Visual Basic Review - ICA
Visual Basic Review - ICAVisual Basic Review - ICA
Visual Basic Review - ICA
 
C lab-programs
C lab-programsC lab-programs
C lab-programs
 
C++ programming
C++ programmingC++ programming
C++ programming
 
Savitch Ch 02
Savitch Ch 02Savitch Ch 02
Savitch Ch 02
 
Savitch Ch 02
Savitch Ch 02Savitch Ch 02
Savitch Ch 02
 
C++ Tutorial.docx
C++ Tutorial.docxC++ Tutorial.docx
C++ Tutorial.docx
 
Prog1-L2.pptx
Prog1-L2.pptxProg1-L2.pptx
Prog1-L2.pptx
 
C++ in 10 Hours.pdf.pdf
C++ in 10 Hours.pdf.pdfC++ in 10 Hours.pdf.pdf
C++ in 10 Hours.pdf.pdf
 
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
 
Savitch ch 02
Savitch ch 02Savitch ch 02
Savitch ch 02
 
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyC++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
 
Lecture 8
Lecture 8Lecture 8
Lecture 8
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2
 
C programming session 02
C programming session 02C programming session 02
C programming session 02
 

More from Sami Mut

C# Tutorial MSM_Murach chapter-17-slides
C# Tutorial MSM_Murach chapter-17-slidesC# Tutorial MSM_Murach chapter-17-slides
C# Tutorial MSM_Murach chapter-17-slidesSami Mut
 
C# Tutorial MSM_Murach chapter-18-slides
C# Tutorial MSM_Murach chapter-18-slidesC# Tutorial MSM_Murach chapter-18-slides
C# Tutorial MSM_Murach chapter-18-slidesSami Mut
 
C# Tutorial MSM_Murach chapter-01-slides
C# Tutorial MSM_Murach chapter-01-slidesC# Tutorial MSM_Murach chapter-01-slides
C# Tutorial MSM_Murach chapter-01-slidesSami Mut
 
chapter 5 Java at rupp cambodia
chapter 5 Java at rupp cambodiachapter 5 Java at rupp cambodia
chapter 5 Java at rupp cambodiaSami Mut
 
chapter 2 Java at rupp cambodia
chapter 2 Java at rupp cambodiachapter 2 Java at rupp cambodia
chapter 2 Java at rupp cambodiaSami Mut
 
chapter 3 Java at rupp cambodia
chapter 3 Java at rupp cambodiachapter 3 Java at rupp cambodia
chapter 3 Java at rupp cambodiaSami Mut
 
chapter 2 Java at rupp cambodia
chapter 2 Java at rupp cambodiachapter 2 Java at rupp cambodia
chapter 2 Java at rupp cambodiaSami Mut
 
chapter 1 Java at rupp cambodia
chapter 1 Java at rupp cambodiachapter 1 Java at rupp cambodia
chapter 1 Java at rupp cambodiaSami Mut
 

More from Sami Mut (9)

C# Tutorial MSM_Murach chapter-17-slides
C# Tutorial MSM_Murach chapter-17-slidesC# Tutorial MSM_Murach chapter-17-slides
C# Tutorial MSM_Murach chapter-17-slides
 
C# Tutorial MSM_Murach chapter-18-slides
C# Tutorial MSM_Murach chapter-18-slidesC# Tutorial MSM_Murach chapter-18-slides
C# Tutorial MSM_Murach chapter-18-slides
 
C# Tutorial MSM_Murach chapter-01-slides
C# Tutorial MSM_Murach chapter-01-slidesC# Tutorial MSM_Murach chapter-01-slides
C# Tutorial MSM_Murach chapter-01-slides
 
MSM_Time
MSM_TimeMSM_Time
MSM_Time
 
chapter 5 Java at rupp cambodia
chapter 5 Java at rupp cambodiachapter 5 Java at rupp cambodia
chapter 5 Java at rupp cambodia
 
chapter 2 Java at rupp cambodia
chapter 2 Java at rupp cambodiachapter 2 Java at rupp cambodia
chapter 2 Java at rupp cambodia
 
chapter 3 Java at rupp cambodia
chapter 3 Java at rupp cambodiachapter 3 Java at rupp cambodia
chapter 3 Java at rupp cambodia
 
chapter 2 Java at rupp cambodia
chapter 2 Java at rupp cambodiachapter 2 Java at rupp cambodia
chapter 2 Java at rupp cambodia
 
chapter 1 Java at rupp cambodia
chapter 1 Java at rupp cambodiachapter 1 Java at rupp cambodia
chapter 1 Java at rupp cambodia
 

Recently uploaded

Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 

Recently uploaded (20)

Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 

C# Tutorial MSM_Murach chapter-04-slides

  • 1. Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 1 Chapter 4 How to work with numeric and string data
  • 2. Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 2 The built-in value types C# .NET keyword Bytes type Description byte 1 Byte Positive integer value from 0 to 255 sbyte 1 SByte Signed integer value from -128 to 127 short 2 Int16 Integer from –32,768 to +32,767 ushort 2 UInt16 Unsigned integer from 0 to 65,535 int 4 Int32 Integer from –2,147,483,648 to +2,147,483,647 uint 4 UInt32 Unsigned integer from 0 to 4,294,967,295 long 8 Int64 Integer from –9,223,372,036,854,775,808 to +9,223,372,036,854,775,807
  • 3. Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 3 The built-in value types (continued) C# .NET keyword Bytes type Description ulong 8 UInt64 Unsigned integer from 0 to +18,446,744,073,709,551,615 float 4 Single Non-integer number with approximately 7 significant digits double 8 Double Non-integer number with approximately 14 significant digits decimal 16 Decimal Non-integer number with up to 28 significant digits (integer and fraction) that can represent values up to 79,228 x 1024 char 2 Char A single Unicode character bool 1 Boolean A true or false value
  • 4. Slide 4 The built-in value types (continued) • The integer data types can be used to store signed and unsigned whole numbers of various sizes. • Since the decimal type is the most accurate non-integer data type, it’s typically used to store monetary values.
  • 5. Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 5 How to declare and initialize a variable in two statements Syntax type variableName; variableName = value; Example int counter; // declaration statement counter = 1; // assignment statement Definition • A variable stores a value that can change as a program executes. Naming conventions • Start the names of variables with a lowercase letter, and capitalize the first letter of each word after the first word. This is known as camel notation.
  • 6. Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 6 How to declare and initialize a variable in one statement Syntax type variableName = value; Examples int counter = 1; long numberOfBytes = 20000; float interestRate = 8.125f; // f or F indicates a float value double price = 14.95; decimal total = 24218.1928m; // m or M indicates a decimal value double starCount = 3.65e+9; // scientific notation char letter = 'A'; // enclose a character value in single quotes bool valid = false; int x = 0, y = 0; // initialize 2 variables with 1 statement
  • 7. Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 7 How to declare and initialize a constant Syntax const type ConstantName = value; Examples const int DaysInNovember = 30; const decimal SalesTax = .075m; Definition • A constant stores a value that can’t be changed. Naming conventions • Capitalize the first letter of each word of a constant name. This is known as Pascal notation.
  • 8. Slide 8 How to declare and initialize variables and constants • Before you can use a variable or constant, you must declare its type and assign an initial value to it. • To declare or initialize more than one variable for a single data type in a single statement, use commas to separate the variable names or assignments. • To identify literal values as float values, you must type the letter f or F after the number. To identify decimal values, you must type the letter m or M after the number. • The keywords for data types must be coded with all lowercase letters.
  • 9. Slide 9 Assignment operator Operator Name Description = Assignment Assigns a new value to the variable. The syntax for a simple assignment statement variableName = expression; Typical assignment statements counter = 7; newCounter = counter; discountAmount = subtotal * .2m; total = subtotal – discountAmount;
  • 10. Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 10 Statements that use the same variable on both sides of the equals sign total = total + 100m; total = total – 100m; price = price * .8m; Statements that use the shortcut assignment operators total += 100m; total -= 100m; price *= .8m;
  • 11. Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 11 Arithmetic operators Operator Name Description + Addition Adds two operands. - Subtraction Subtracts the right operand from the left operand. * Multiplication Multiplies the right operand and the left operand. / Division Divides the right operand into the left operand. If both operands are integers, then the result is an integer. % Modulus Returns the value that is left over after dividing the right operand into the left operand.
  • 12. Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 12 Arithmetic operators (continued) Operator Name Description + Positive sign Returns the value of the operand. - Negative sign Changes a positive value to negative, and vice versa. ++ Increment Adds 1 to the operand (x = x + 1). -- Decrement Subtracts 1 from the operand (x = x - 1).
  • 13. Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 13 Arithmetic expressions that use integers int x = 14; int y = 8; int result1 = x + y; // result1 = 22 int result2 = x - y; // result2 = 6 int result3 = x * y; // result3 = 112 int result4 = x / y; // result4 = 1 int result5 = x % y; // result5 = 6 int result6 = -y + x; // result6 = 6 int result7 = --y; // result7 = 7 int result8 = ++x; // result8 = 15, x = 15
  • 14. Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 14 Arithmetic expressions that use decimal values decimal a = 8.5m; decimal b = 3.4m; decimal result11 = a + b; // result11 = 11.9 decimal result12 = a - b; // result12 = 5.1 decimal result13 = a / b; // result13 = 2.5 decimal result14 = a * b; // result14 = 28.90 decimal result15 = a % b; // result15 = 1.7 decimal result16 = -a; // result16 = -8.5 decimal result17 = --a; // result17 = 7.5 decimal result18 = ++b; // result18 = 4.4 Arithmetic expressions that use characters char letter1 = 'C'; // letter1 = 'C' // Unicode integer is 67 char letter2 = ++letter1; // letter2 = 'D' // Unicode integer is 68
  • 15. Slide 15 What is the value of the “a”? decimal a = 2 + 3 * 4 + 5;
  • 16. Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 16 The order of precedence for arithmetic operations 1. Increment and decrement 2. Positive and negative 3. Multiplication, division, and modulus 4. Addition and subtraction
  • 17. Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 17 A calculation that uses the default order of precedence decimal discountPercent = .2m; // 20% discount decimal price = 100m; // $100 price price = price * 1 – discountPercent; // price = $99.8 A calculation that uses parentheses to specify the order of precedence decimal discountPercent = .2m; // 20% discount decimal price = 100m; // $100 price price = price * (1 – discountPercent); // price = $80 Examples that use prefixed and postfixed increment and decrement operators int a = 5; int b = 5 int y = ++a; // a = 6, y = 6 int z = b++; // b = 6, z = 5
  • 18. Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 18 Five static methods of the Math class The syntax of the Round method Math.Round(decimalNumber[, precision]) The syntax of the Pow method Math.Pow(number, power) The syntax of the Sqrt method Math.Sqrt(number) The syntax of the Min and Max methods Math.{Min|Max}(number1, number2) There are many, many more…
  • 19. Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 19 Statements that use static methods of the Math class int shipWeight = Math.Round(shipWeightDouble); // round to a whole number double orderTotal = Math.Round(orderTotal, 2); // round to 2 decimal places double area = Math.Pow(radius, 2) * Math.PI; // area of circle double sqrtX = Math.Sqrt(x); double maxSales = Math.Max(lastYearSales, thisYearSales); int minQty = Math.Min(lastYearQty, thisYearQty);
  • 20. Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 20 Results from static methods of the Math class Statement Result Math.Round(23.75) 24 Math.Round(23.5) 24 Math.Round(24.5) 24 Math.Round(23.754, 2) 23.75 Math.Round(23.755, 2) 23.76 Math.Pow(5, 2) 25 Math.Sqrt(20.25) 4.5 Math.Max(23.75, 20.25) 23.75 Math.Min(23.75, 20.25) 20.25
  • 21. Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 21 How to declare and initialize a string string message1 = "Invalid data entry."; string message2 = ""; string message3 = null; How to join strings string firstName = "Bob"; // firstName is "Bob" string lastName = "Smith"; // lastName is "Smith" string name = firstName + " " + lastName; // name is "Bob Smith" How to join a string and a number double price = 14.95; string priceString = "Price: $" + price; // priceString is "Price: $14.95"
  • 22. Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 22 How to append one string to another string string firstName = "Bob"; // firstName is "Bob" string lastName = "Smith"; // lastName is "Smith" string name = firstName + " "; // name is "Bob " name = name + lastName; // name is "Bob Smith" How to append one string to another with the += operator string firstName = "Bob"; // firstName is "Bob" string lastName = "Smith"; // lastName is "Smith" string name = firstName + " "; // name is "Bob " name += lastName; // name is "Bob Smith"
  • 23. Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 23 Common methods for data conversion Method Description ToString([format]) A method that converts the value to its equivalent string representation using the specified format. If the format is omitted, the value isn’t formatted. Parse(string) A static method that converts the specified string to an equivalent data value.
  • 24. Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 24 Some of the static methods of the Convert class Method Description ToDecimal(value) Converts the value to the decimal data type. ToDouble(value) Converts the value to the double data type. ToInt32(value) Converts the value to the int data type. ToChar(value) Converts the value to the char data type. ToBool(value) Converts the value to the bool data type. ToString(value) Converts the value to a string object.
  • 25. Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 25 Statements that use ToString and Parse decimal sales = 2574.98m; string salesString = sales.ToString(); // decimal to string sales = Decimal.Parse(salesString); // string to decimal An implicit call of the ToString method double price = 49.50; string priceString = "Price: $" + price; // automatic ToString call Conversion statements that use the Convert class decimal subtotal = Convert.ToDecimal(txtSubtotal.Text); // string to decimal int years = Convert.ToInt32(txtYears.Text); // string to int txtSubtotal.Text = Convert.ToString(subtotal); // decimal to string int subtotalInt = Convert.ToInt32(subtotal); // decimal to int
  • 26. Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 26 Standard numeric formatting codes Code Format C or c Currency P or p Percent N or n Number F or f Float D or d Digits E or e Exponential G or g General
  • 27. Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 27 How to use the ToString method to format a number Statement Example string monthlyAmount = amount.ToString("c"); $1,547.20 string interestRate = interest.ToString("p1"); 2.3% string quantityString = quantity.ToString("n0"); 15,000 string paymentString = payment.ToString("f3"); 432.818
  • 28. Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 28 How to use the Format method of the String class to format a number Statement Result string monthlyAmount = String.Format("{0:c}", 1547.2m); $1,547.20 string interestRate = String.Format("{0:p1}", .023m); 2.3% string quantityString = String.Format("{0:n0}", 15000); 15,000 string paymentString = String.Format("{0:f3}", 432.8175); 432.818 The syntax of the format specification used by the Format method {index:formatCode}
  • 29. Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 29 The Invoice Total form
  • 30. Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 30 The controls on the Invoice Total form that are referred to in the code Object type Name Description TextBox txtSubtotal A text box that accepts a subtotal amount TextBox txtDiscountPercent A read-only text box that displays the discount percent TextBox txtDiscountAmount A read-only text box that displays the discount amount TextBox txtTotal A read-only text box that displays the invoice total Button btnCalculate Calculates the discount amount and invoice total when clicked Button btnExit Closes the form when clicked
  • 31. Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 31 The event handlers for the Invoice Total form private void btnCalculate_Click(object sender, System.EventArgs e) { decimal subtotal = Convert.ToDecimal(txtSubtotal.Text); decimal discountPercent = .25m; decimal discountAmount = subtotal * discountPercent; decimal invoiceTotal = subtotal - discountAmount; txtDiscountPercent.Text = discountPercent.ToString("p1"); txtDiscountAmount.Text = discountAmount.ToString("c"); txtTotal.Text = invoiceTotal.ToString("c"); txtSubtotal.Focus(); } private void btnExit_Click(object sender, System.EventArgs e) { this.Close(); }
  • 32. Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 32 The enhanced Invoice Total form
  • 33. Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 33 The code for the class variables and two event handlers int numberOfInvoices = 0; decimal totalOfInvoices = 0m; decimal invoiceAverage = 0m; private void btnCalculate_Click(object sender, EventArgs e) { decimal subtotal = Convert.ToDecimal(txtEnterSubtotal.Text); decimal discountPercent = .25m; decimal discountAmount = Math.Round(subtotal * discountPercent, 2); decimal invoiceTotal = subtotal - discountAmount; txtSubtotal.Text = subtotal.ToString("c"); txtDiscountPercent.Text = discountPercent.ToString("p1"); txtDiscountAmount.Text = discountAmount.ToString("c"); txtTotal.Text = invoiceTotal.ToString("c");
  • 34. Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 34 The class variables and two event handlers (cont.) numberOfInvoices++; totalOfInvoices += invoiceTotal; invoiceAverage = totalOfInvoices / numberOfInvoices; txtNumberOfInvoices.Text = numberOfInvoices.ToString(); txtTotalOfInvoices.Text = totalOfInvoices.ToString("c"); txtInvoiceAverage.Text = invoiceAverage.ToString("c"); txtEnterSubtotal.Text = ""; txtEnterSubtotal.Focus(); }
  • 35. Murach’s C# 2010, C4 © 2010, Mike Murach & Associates, Inc. Slide 35 The class variables and two event handlers (cont.) private void btnClearTotals_Click(object sender, System.EventArgs e) { numberOfInvoices = 0; totalOfInvoices = 0m; invoiceAverage = 0m; txtNumberOfInvoices.Text = ""; txtTotalOfInvoices.Text = ""; txtInvoiceAverage.Text = ""; txtEnterSubtotal.Focus(); }