Home > Articles > Programming > C#

This chapter is from the book

4.11 Floating-Point Numbers and Type decimal

In our next application, we depart temporarily from our GradeBook case study to declare a class called Account that maintains a bank account's balance. Most account balances are not whole numbers (such as 0, –22 and 1024). For this reason, class Account represents the account balance as a real number (i.e., a number with a decimal point, such as 7.33, 0.0975 or 1000.12345). C# provides three simple types for storing real numbers—float, double , and decimal. Types float and double are called floating-point types. The primary difference between them and decimal is that decimal variables store a limited range of real numbers precisely, whereas floating-point variables store only approximations of real numbers, but across a much greater range of values. Also, double variables can store numbers with larger magnitude and finer detail (i.e., more digits to the right of the decimal point—also known as the number's precision) than float variables. A key application of type decimal is representing monetary amounts.

Real-Number Precision and Storage Requirements

Variables of type float represent single-precision floating-point numbers and have seven significant digits. Variables of type double represent double-precision floating-point numbers. These require twice as much storage as float variables and provide 15–16 significant digits—approximately double the precision of float variables. Furthermore, variables of type decimal require twice as much storage as double variables and provide 28–29 significant digits. In some applications, even variables of type double and decimal will be inadequate—such applications are beyond the scope of this book.

Most programmers represent floating-point numbers with type double. In fact, C# treats all real numbers you type in an application's source code (such as 7.33 and 0.0975) as double values by default. Such values in the source code are known as floating-point literals. To type a decimal literal, you must type the letter "M" or "m" (which stands for "money") at the end of a real number (for example, 7.33M is a decimal literal rather than a double). Integer literals are implicitly converted into type float, double or decimal when they're assigned to a variable of one of these types. See Appendix B for the ranges of values for floats, doubles, decimals and all the other simple types.

Although floating-point numbers are not always 100% precise, they have numerous applications. For example, when we speak of a "normal" body temperature of 98.6, we do not need to be precise to a large number of digits. When we read the temperature on a thermometer as 98.6, it may actually be 98.5999473210643. Calling this number simply 98.6 is fine for most applications involving body temperatures. Due to the imprecise nature of floating-point numbers, type decimal is preferred over the floating-point types whenever the calculations need to be exact, as with monetary calculations. In cases where approximation is enough, double is preferred over type float because double variables can represent floating-point numbers more accurately. For this reason, we use type decimal throughout the book for monetary amounts and type double for other real numbers.

Real numbers also arise as a result of division. In conventional arithmetic, for example, when we divide 10 by 3, the result is 3.3333333..., with the sequence of 3s repeating infinitely. The computer allocates only a fixed amount of space to hold such a value, so clearly the stored floating-point value can be only an approximation.

Account Class with an Instance Variable of Type decimal

Our next application (Figs. 4.15–4.16) contains a simple class named Account (Fig. 4.15) that maintains the balance of a bank account. A typical bank services many accounts, each with its own balance, so line 7 declares an instance variable named balance of type decimal. Variable balance is an instance variable because it's declared in the body of the class (lines 6–36) but outside the class's method and property declarations (lines 10–13, 16–19 and 22–35). Every instance (i.e., object) of class Account contains its own copy of balance.

Fig 4.15. Account class with a constructor to initialize instance variable balance.

 1  // Fig. 4.15: Account.cs
 2  // Account class with a constructor to
 3  // initialize instance variable balance.
 4
 5  public class Account
 6  {
 7     private decimal balance; // instance variable that stores the balance
 8
 9     // constructor
10     public Account(  decimal  initialBalance )
11     {
12        Balance = initialBalance;  // set balance using property
13     }  // end Account constructor
14
15     // credit (add) an amount to the account
16     public void Credit( decimal amount )
17     {
18        Balance = Balance + amount;  // add amount to balance
19     }  // end method Credit
20
21     // a property to get and set the account balance
22     public decimal Balance
23     {
24        get
25        {
26           return balance;
27        }  // end get
28        set
29        {
30           // validate that value is greater than or equal to 0;
31           // if it is not, balance is left unchanged
32            if ( value >=  0 )
33              balance = value;
34        }  // end set
35     }  // end property Balance
36  }  // end class Account

Fig 4.16. Create and manipulate an Account object.

 1  // Fig. 4.16: AccountTest.cs
 2  // Create and manipulate Account objects.
 3  using System;
 4
 5  public class AccountTest
 6  {
 7     // Main method begins execution of C# application
 8     public static void Main( string[] args )
 9     {
10        Account account1 = new Account( 50.00M ); // create Account object
11        Account account2 = new Account( -7.53M ); // create Account object
12
13        // display initial balance of each object using a property
14        Console.WriteLine( "account1 balance: " {0:C},
15           account1.Balance ); // display Balance property
16        Console.WriteLine( "account2 balance: {0:C} \n",
17           account2.Balance ); // display Balance property
18
19        decimal depositAmount; // deposit amount read from user
20
21        // prompt and obtain user input
22        Console.Write( "Enter deposit amount for account1: " );
23        depositAmount = Convert.ToDecimal( Console.ReadLine() );
24        Console.WriteLine( "adding  {0:C} to account1 balance\n",
25           depositAmount );
26        account1.Credit( depositAmount ); // add to account1 balance
27
28        // display balances
29        Console.WriteLine( "account1 balance:  {0:C} ",
30           account1.Balance );
31        Console.WriteLine( "account2 balance:  {0:C} \n",
32           account2.Balance );
33
34        // prompt and obtain user input
35        Console.Write( "Enter deposit amount for account2: " );
36        depositAmount = Convert.ToDecimal( Console.ReadLine() );
37        Console.WriteLine( "adding {0:C} to account2 balance\n",
38           depositAmount );
39        account2.Credit( depositAmount );  // add to account2 balance
40
41        // display balances
42        Console.WriteLine( "account1 balance: {0:C} ", account1.Balance );
43        Console.WriteLine( "account2 balance: {0:C} ", account2.Balance );
44     }  // end Main
45  }  // end class AccountTest

Class Account contains a constructor, a method, and a property. Since it's common for someone opening an account to place money in the account immediately, the constructor (lines 10–13) receives a parameter initialBalance of type decimal that represents the account's starting balance. Line 12 assigns initialBalance to the property Balance, invoking Balance's set accessor to initialize the instance variable balance.

Method Credit (lines 16–19) doesn't return data when it completes its task, so its return type is void. The method receives one parameter named amount—a decimal value that's added to the property Balance. Line 18 uses both the get and set accessors of Balance. The expression Balance + amount invokes property Balance's get accessor to obtain the current value of instance variable balance, then adds amount to it. We then assign the result to instance variable balance by invoking the Balance property's set accessor (thus replacing the prior balance value).

Property Balance (lines 22–35) provides a get accessor, which allows clients of the class (i.e., other classes that use this class) to obtain the value of a particular Account object's balance. The property has type decimal (line 22). Balance also provides an enhanced set accessor.

In Section 4.5, we introduced properties whose set accessors allow clients of a class to modify the value of a private instance variable. In Fig. 4.7, class GradeBook defines property CourseName's set accessor to assign the value received in its parameter value to instance variable courseName (line 19). This CourseName property does not ensure that courseName contains only valid data.

The application of Figs. 4.15–4.16 enhances the set accessor of class Account's property Balance to perform this validation (also known as validity checking). Line 32 (Fig. 4.15) ensures that value is nonnegative. If the value is greater than or equal to 0, the amount stored in value is assigned to instance variable balance in line 33. Otherwise, balance is left unchanged.

AccountTest Class to Use Class Account

Class AccountTest (Fig. 4.16) creates two Account objects (lines 10–11) and initializes them respectively with 50.00M and -7.53M (the decimal literals representing the real numbers 50.00 and -7.53). The Account constructor (lines 10–13 of Fig. 4.15) references property Balance to initialize balance. In previous examples, the benefit of referencing the property in the constructor was not evident. Now, however, the constructor takes advantage of the validation provided by the set accessor of the Balance property. The constructor simply assigns a value to Balance rather than duplicating the set accessor's validation code. When line 11 of Fig. 4.16 passes an initial balance of -7.53 to the Account constructor, the constructor passes this value to the set accessor of property Balance, where the actual initialization occurs. This value is less than 0, so the set accessor does not modify balance, leaving this instance variable with its default value of 0.

Lines 14–17 in Fig. 4.16 output the balance in each Account by using the Account's Balance property. When Balance is used for account1 (line 15), the value of account1's balance is returned by the get accessor in line 26 of Fig. 4.15 and displayed by the Console.WriteLine statement (Fig. 4.16, lines 14–15). Similarly, when property Balance is called for account2 from line 17, the value of the account2's balance is returned from line 26 of Fig. 4.15 and displayed by the Console.WriteLine statement (Fig. 4.16, lines 16–17). The balance of account2 is 0 because the constructor ensured that the account could not begin with a negative balance. The value is output by WriteLine with the format item {0:C}, which formats the account balance as a monetary amount. The : after the 0 indicates that the next character represents a format specifier, and the C format specifier after the : specifies a monetary amount (C is for currency). The cultural settings on the user's machine determine the format for displaying monetary amounts. For example, in the United States, 50 displays as $50.00. In Germany, 50 displays as 50,00 €. Figure 4.17 lists a few other format specifiers in addition to C.

Fig 4.17. string format specifiers.

Format specifier

Description

C or c

Formats the string as currency. Displays an appropriate currency symbol ($ in the U.S.) next to the number. Separates digits with an appropriate separator character (comma in the U.S.) and sets the number of decimal places to two by default.

D or d

Formats the string as a whole number. Displays number as an integer.

N or n

Formats the string with a thousands separator and a default of two decimal places.

E or e

Formats the number using scientific notation with a default of six decimal places.

F or f

Formats the string with a fixed number of decimal places (two by default).

G or g

Formats the number normally with decimal places or using scientific notation, depending on context. If a format item does not contain a format specifier, format G is assumed implicitly.

X or x

Formats the string as hexadecimal.

Line 19 declares local variable depositAmount to store each deposit amount entered by the user. Unlike the instance variable balance in class Account, the local variable depositAmount in Main is not initialized to 0 by default. Also, a local variable can be used only in the method in which it's declared. However, this variable does not need to be initialized here because its value will be determined by the user's input. The compiler does not allow a local variable's value to be read until it's initialized.

Line 22 prompts the user to enter a deposit amount for account1. Line 23 obtains the input from the user by calling the Console class's ReadLine method, then passing the string entered by the user to the Convert class's ToDecimal method, which returns the decimal value in this string. Lines 24–25 display the deposit amount. Line 26 calls object account1's Credit method and supplies depositAmount as the method's argument. When the method is called, the argument's value is assigned to parameter amount of method Credit (lines 16–19 of Fig. 4.15), then method Credit adds that value to the balance (line 18 of Fig. 4.15). Lines 29–32 (Fig. 4.16) output the balances of both Accounts again to show that only account1's balance changed.

Line 35 prompts the user to enter a deposit amount for account2. Line 36 obtains the input from the user by calling method Console.ReadLine, and passing the return value to the Convert class's ToDecimal method. Lines 37–38 display the deposit amount. Line 39 calls object account2's Credit method and supplies depositAmount as the method's argument, then method Credit adds that value to the balance. Finally, lines 42–43 output the balances of both Accounts again to show that only account2's balance changed.

set and get Accessors with Different Access Modifiers

By default, the get and set accessors of a property have the same access as the property—for example, for a public property, the accessors are public. It's possible to declare the get and set accessors with different access modifiers. In this case, one of the accessors must implicitly have the same access as the property and the other must be declared with a more restrictive access modifier than the property. For example, in a public property, the get accessor might be public and the set accessor might be private. We demonstrate this feature in Section 10.5.

UML Class Diagram for Class Account

The UML class diagram in Fig. 4.18 models class Account of Fig. 4.15. The diagrammodels the Balance property as a UML attribute of type decimal (because the corresponding C# property had type decimal). The diagram models class Account's constructor with a parameter initialBalance of type decimal in the third compartment of the class. The diagram models operation Credit in the third compartment with an amount parameter of type decimal (because the corresponding method has an amount parameter of C# type decimal).

Fig. 4.18

Fig. 4.18 UML class diagram indicating that class Account has a public Balance property of type decimal, a constructor and a method.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020