Introduction to Floating-Point Numbers

Overview

A real number is a number that can display two sections separated by a decimal separator or decimal symbol. In US English, the separator is the period:

Regional

On both sides of the decimal symbol, digits are used to specify the value of the number. The number of digits on the right side of the symbol determines the precision of the number.

Practical LearningPractical Learning: Introducing Floating-Point Numbers

  1. Start Microsoft Visual Studio
  2. On the main menu, click File -> New -> Project...
  3. In the New Project dialog box, click ASP.NET Web Application (.NET Framework) and set the Name to SweetStarClothiers3
  4. Click OK
  5. In the Templates list of the New ASP.NET Web Application dialog box, click the MVC icon and click OK
  6. In the Solution Explorer, right-click the Content folder, -> Add -> New Item...
  7. In the left frame of the Add New Item dialog box, make sure the Web node is selected.
    In the right frame, click Style Sheet
  8. Change the Name of the file to StarClothiers
  9. Click Add
  10. Create the following styles in the document:
    body {
        margin: 0;
        padding: 0;
    }
    
    #top-banner {
        top: 0;
        width: 100%;
        height: 3em;
        background-color: #113d8b;
        border: 0px dashed #ff6a00;
    }
    
    #top-tool-range {
        padding-top: 8px;
        margin: auto;
        width: 500px;
    }
    
    .top-menu-item {
        margin-top: 5px;
        padding-top: 25px;
        padding-right: 10px;
        padding-bottom: 10px;
        padding-left: 10px;
        width: 120px;
        color: azure;
        font-size: 1.18em;
        border: 1px solid #113d8b;
    }
    
    a.top-menu-item:hover {
        text-decoration: none;
        color: yellow;
    }
    
    .jumbotron {
        font-size: 18px;
        font-weight: 600;
        padding-top: 10px;
        padding-bottom: 10px;
        background-color: #5da2cf;
    }
    
    .jumbotron h1 {
        font-size: 41px;
        color: antiquewhite;
    }
    
    .jumbotron h2 {
        font-size: 31px;
        color: #d7d893;
    }
    
    .jumbotron p {
        font-size: 21px;
        color: ghostwhite;
    }
    
    .container .jumbotron {
        border-top-left-radius: 0px;
        border-top-right-radius: 0px;
        border-bottom-left-radius: 15px;
        border-bottom-right-radius: 15px;
    }
  11. In the Solution Explorer, right-click Controllers -> Add -> New Scaffolded Item...
  12. In the middle frame of the Add Scaffold dialog box, click MVC 5 Controller - Empty
  13. Click Add
  14. Type Depreciations to get DepreciationsControllers
  15. Click Add
  16. Create the following methods in the document:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace SweetStarClothiers2.Controllers
    {
        public class DepreciationsController : Controller
        {
            // GET: Depreciations
            public ActionResult Index()
            {
                return View();
            }
    
            // GET: StraightLineMethod
            public ActionResult StraightLineMethod()
            {
                return View();
            }
    
            // GET: UnitsOfProduction
            public ActionResult UnitsOfProduction()
            {
                return View();
            }
        }
    }
  17. In the Solution Explorer, under Views, right-click Depreciations -> Add -> View...
  18. Type Index as the View Name
  19. Click Add
  20. In the Solution Explorer, under Views, right-click Depreciations -> Add -> View...
  21. Type StraightLineMethod as the View Name
  22. Click Add
  23. In the Solution Explorer, under Views, right-click Depreciations -> Add -> View...
  24. Type UnitsOfProduction as the View Name
  25. Press Enter
  26. Change the document as follows:
    @{
        ViewBag.Title = "Depreciation: Units of Production";
    }
    
    <h2>Depreciation: Units of Production</h2>
    
    @{
    
        if (IsPost)
        {
            
        }
    }
    
    @using (Html.BeginForm())
    {
        <table>
            <tr>
                <td width="120">@Html.Label("txtMachineCost", "Machine Cost:", new { style = "font-weight: bold;" })</td>
                <td>@Html.TextBox("txtMachineCost", "")</td>
            </tr>
            <tr>
                <td>@Html.Label("txtEstimateLife", "Estimate Life:", new { style = "font-weight: bold;" })</td>
                <td>@Html.TextBox("txtEstimateLife", "")</td>
            </tr>
            <tr>
                <td>@Html.Label("txtNumberOfUnits", "Number of Units:", new { style = "font-weight: bold;" })</td>
                <td>@Html.TextBox("txtNumberOfUnits", "") 
                    <select name="cbxUnits">
                      <option>Hours</option>
                      <option>Miles</option>
                      <option>Units</option>
                    </select></td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td><input name="btnCalculate" type="submit" value="Calculate" /></td>
            </tr>
            <tr>
                <td>@Html.Label("txtDepreciation", "Depreciation:", new { style = "font-weight: bold;" })</td>
                <td>@Html.TextBox("txtDepreciation", "")</td>
            </tr>
        </table>
    }
  27. In the Solution Explorer, under Views, expand Home
  28. Under Home, double-click Index.cshtml
  29. Change the document as follows:
    @{
        ViewBag.Title = "Introduction";
    }
    
    <div class="jumbotron">
        <h1>Sweet Star Clothiers</h1>
        <h2>Business Machines</h2>
        <p class="lead">This is the website from which Sweet Star Clothiers evaluates the evolutionary 
        life span of its machines. To conduct its day-to-day operations, the company owns or rents a few
        business machines such as industrial sewing machines, fabric care machines, etc. On this 
        internal website, the company perfoms various types of calculations with regards to machine 
        maintaining and/or in planning to replace the machines.</p>
        <p>@Html.ActionLink("Get more information from SSC Management", "Index", "Depreciations", null, new { @class = "btn btn-primary btn-lg" })</p>
    </div>
    
    <div class="row">
        <div class="col-md-4">
            <h2>Machine Acquisition</h2>
            <p>
                If you are interested, you can find out what machines Sweet Star Clothiers uses for its 
                day-to-day operations. You can also find out how SSC acquires (purchases or rents) its 
                machines. This site also provides some information about the machines standard and 
                manufacturers warranties.
            </p>
            <p>@Html.ActionLink("Learn more", "StraightLineMethod", "Depreciations", null, new { @class = "btn btn-default" }) &raquo;</p>
        </div>
        <div class="col-md-4">
            <h2>Straight-Line Method</h2>
            <p>In this section, for both business and legal purpose, SSC demonstrates how its management 
            teacm calculates the depreciation of its machines using the Straight-Line Method.</p>
            <p>@Html.ActionLink("Straight-Line Method", "StraightLineMethod", "Depreciations", null, new { @class = "btn btn-default" }) &raquo;</a></p>
        </div>
        <div class="col-md-4">
            <h2>Units of Production</h2>
            <p>Some of the machines used by SSC are made to produce a certain number of items as units (such 
            as shirts, pants, dresses, blazers, etc) or to do their jobs for a certain time (hours, 
            months, years, etc). For accounting and legal (taxes) purposes, the company must factor such 
            details when evaluating the lifetime of the machine.</p>
            <p>@Html.ActionLink("Units of Production", "UnitsOfProduction", "Depreciations", null, new { @class = "btn btn-default" }) &raquo;</a></p>
        </div>
    </div>
  30. In the Solution Explorer, under Views, expand Shared
  31. Double-click _Layout.cshtml to open it
  32. Change the document as follows:
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sweet Star Clothiers :: @ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    <link rel="stylesheet" type="text/css" href="~/Content/StarClothiers.css" />
    </head>
    <body>
    <div id="top-banner">
        <div id="top-tool-range">
            @Html.ActionLink("Home", "Index", "Home", new { @class = "top-menu-item" })
            @Html.ActionLink("Depreciations", "Index", "Depreciations", new { value = "Nothing" }, new { @class = "top-menu-item" })
            @Html.ActionLink("About SSC", "About", "Home", new { @class = "top-menu-item" })
            @Html.ActionLink("Contact Us", "Contact", "Home", new { @class = "top-menu-item" })
        </div>
    </div>
    
    <div class="container body-content">
            @RenderBody()
            <hr />
            <footer>
                <h4 class="text-center">&copy; @DateTime.Now.Year -- Sweet Star Clothiers --</h4>
            </footer>
    </div>
    
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/bootstrap")
        @RenderSection("scripts", required: false)
    </body>
    </html>
  33. Access the Index.cshtml file and, to execute the application, press Ctrl + F5:

    Introduction to Floating-Point Numbers

  34. Click the Units of Production button:

    Introduction to Floating-Point Numbers

  35. Close the browser and return to your programming environment

The Floating Type

The most fundamental floating-point type is named float. Its equivalent in the .NET Framework is a structure named Single. A variable declared as float or Single can store real numbers that range from -3.4 x 1038 to 3.4 x 1038 with a precision of 7 digits. Here is an example:

@{
    float distance;
}

You can also declare the varialbe using the var or the dynamic keyword.

Floating-Point Numbers in a Drawing Point

We saw that the Point structure uses integral numbers to hold the coordinates of a point. Some operations require that the coordinates be given with more precision in a floating-point format. To support this, the .NET Framework provides a structure named PointF. It follows the same description as its equivalent Point counterpart, using the same Empty field, the same properties, the same methods, and the same constructors. The X and Y properties of the PointF structure are of type float:

Axes of the Windows Coordinate System

Floating-Point Numbers in a Drawing Size

We already know that the size of an object is a combination of its width and height. To make these distances simple, the .NET Framework provides the Size structure. To support distances that require more precision, the .NET Framework provides a structure named SizeF. Both structures are defined in the System.Drawing namespace. The SizeF structure is built like its Size counterpart. All values used in the properties, the methods, and the constructors of the SizeF structure are of type float

Floating-Point Numbers in a Rectangle

The combination of the location and size of an object is represented as a rectangle: a geometric figure with four sides and four right angles. As we know already, to support this figure, the System.Drawing namespace provides the Rectangle structure. To support floating numbers in a rectangle, the .NET Framework provides a structure named RectangleF.

The RectangleF structure is built like the Rectangle structure except that all its members use the float (or Single) type. When the Rectangle structure uses members or values of type Point or Size, the RectangleF structure uses values of type PointF or SizeF. For example, the RectangleF constructor uses the following syntax:

public RectangleF(PointF location, SizeF size);

This constructor requires that you define a PointF and a SizeF values in order to use it.

The RectangleF structure has another constructor as follows:

public RectangleF(float x, float y, float width, float height);

Floating-Point Numbers with Double Precision

Introduction

To support values that are larger than the float type can handle and require more precision, the C# language provides a data type named double. You can use it or use the var or the dynamic keyword to declare a variable for a decimal number.

To provide the value of a real number, start with the whole side, followed by the decimal separator, and ending with the fraction side. Here are examples:

@{
    var constant = 0.9023;
    dynamic evolution = 0.58350;
}

<ul>
    <li>Constant: @constant</li>
    <li>Evolution: @evolution</li>
</ul>
}

If the whole part of the number is 0, that is a number between 0 and 1, you can omit the 0. Here are examples:

@{ 
    var     constant  = .9023;
    dynamic evolution = .58350;
}

<ul>
    <li>Constant: @constant</li>
    <li>Evolution: @evolution</li>
</ul>
}

A variable declared as double uses very large numbers ranging from 5.0 x 10−324 to 1.7 x 10308 with a precision of 15 or 16 digits. Because the double data type provides a better result with better precision than the float type, whenever you declare a variable using either the var or the float keyword and assign it a value, the compiler allocates memory for a double. If you insist on the variable being treated as float, when assigning it a value, add an f or an F suffix to the value. Here is an example:

@{
    float distance;
		
    distance = 248.38F;
}

On the other hand, if you want a value to be treated with double-precision, add a d or a D suffix to it. Here is an example:

@{
    var  number = 62834.9023D;
}

Real Decimal Numbers

In previous lessons, we got acquainted with the decimal data type that can be used to declare a variable for small or significantly large numbers. A value stored in a decimal variable can range between 1.0 x 10−28 and 7.9 x 1028 with a precision of 28 to 29 digits.

After declaring a decimal variable, you can initialize it with a natural number. To indicate that the variable holds a decimal value, when initializing it, add an m or an M suffix to its value. Here is an example:

@{
    decimal hourlySalary;
		
	hourlySalary = 24.25M;
}

Topics on Floating-Point Numbers

Using the Right Type of Value

As seen in previous sections and this one, when declaring and initializing a real variable, the suffix you give to its assigned value indicates to the compiler the actual type of value and the type of memory that would be allocated for the variable:

Getting a Floating-Point Number

Parsing a Floating-Point Number

When a visitor types something in a control or makes a selection, the value the user gets is an object or a string. If you want to treat such a value as a number, you must first convert it. As one way to assist you, the structure of each data type is equipped with a static method named Parse. Still, if the visitor provides an invalid value, the browser may produce an error. To provide an alternative, the structure of each data type is equipped with the TryParse() method.

Practical LearningPractical Learning: Parsing a Floating-Point Number

  1. Access the UnitsOfProduction.cshtml file and change its document as follows:
    @{
        ViewBag.Title = "Depreciation: Units of Production";
    }
    
    <h2>Depreciation: Units of Production</h2>
    
    @{
        string units = "";
        int estimatedLife = 0;
        int numberOfUnits = 0;
        double machineCost = 0;
        string strDepreciation = "";
    
        if (IsPost)
        {
            units = Request["cbxUnits"];
            machineCost = double.Parse(Request["txtMachineCost"]);
            estimatedLife = int.Parse(Request["txtEstimateLife"]);
            numberOfUnits = int.Parse(Request["txtNumberOfUnits"]);
    
            double depreciation = (machineCost - estimatedLife) / numberOfUnits;
    
            if( units == "Hours")
            {
                strDepreciation = depreciation.ToString() + "/Hour";
            }
            else if( units == "Miles")
            {
                strDepreciation = depreciation.ToString() + "/Mile";
            }
            else // if (units == "Units")
            {
                strDepreciation = depreciation.ToString() + "/Unit";
            }
        }
    }
    
    @using (Html.BeginForm())
    {
        <table>
            <tr>
                <td width="120">@Html.Label("txtMachineCost", "Machine Cost:", new { style = "font-weight: bold;" })</td>
                <td>@Html.TextBox("txtMachineCost", @machineCost)</td>
            </tr>
            <tr>
                <td>@Html.Label("txtEstimatedLife", "Estimated Life:", new { style = "font-weight: bold;" })</td>
                <td>@Html.TextBox("txtEstimatedLife", @estimatedLife)</td>
            </tr>
            <tr>
                <td>@Html.Label("txtNumberOfUnits", "Number of Units:", new { style = "font-weight: bold;" })</td>
                <td>@Html.TextBox("txtNumberOfUnits", @numberOfUnits)
                    <select name="cbxUnits">
                      <option value="Hours">Hours</option>
                      <option value="Miles">Miles</option>
                      <option value="Units">Units</option>
                    </select></td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td><input name="btnCalculate" type="submit" value="Calculate" /></td>
            </tr>
            <tr>
                <td>@Html.Label("txtDepreciation", "Depreciation:", new { style = "font-weight: bold;" })</td>
                <td>@Html.TextBox("txtDepreciation", @strDepreciation)</td>
            </tr>
        </table>
    }
  2. To execute, on the main menu, click Debug -> Start Without Debugging
  3. Close the browser and return to your programming environment

Converting a Value

To assist you in converting a value, the static Convert classic is equipped with a method that can be used to convert a value to the appropriate type.

Floating-Point Constants

The Minimum and Maximum Values

When initializing a floating-point variable, you should make sure you assign it a value that can fit in the memory allocated for it. As mentioned for the integer data types, the minimum value that a float variable can hold is represented by the MinValue constant of the Single structure and the MinValue field of the Double. The maximum value that a float or a double variable can hold is named MaxValue.

When the Value is Not-A-Number

After declaring and initializing a float or a double variable, it should hold an appropriate value. If you get the variable value some other way, at one time or another, you may not know what value is stored in the memory allocated for the variable. In fact, the variable may hold a value that is not a number. To let you check whether the variable is holding a value that is not a number, the structures of the floating-point types are equipped with a constant named NaN. To get its information, type the float or the double data type, followed by the period operator, and followed by the NaN constant. Here is an example:

@{
    double number = 0D;

	if( number == double.NaN ) {
	    <p>The value is not a number</p>;
    }
}

Another technique you can use to check this characteristic is to call the IsNaN() method of either the Single or the Double structure.

The Epsilon Constant

Using one integer and one floating-point number, or with two floating-point numbers, you can perform one of the routine arithmetic operations such as the addition, the subtraction, the multiplication, or the division. When it comes to the division and if performed on two constants, you can get a positive or a negative number. In highly precise calculations, you may have to deal with an approximate number whose exact value is not known. For example, the smallest positive number is called epsilon. In the Double and the Single structures, this constant is named Epsilon. For the single-precision type, the epsilon is equal to 1.445. For a double-precision type, the epsilon constant is equivalent to 4.94065645841247-324. As you can see, this number is extremely low.

The Negative Infinity

When dealing with real numbers, some operations produce very little or very large numbers. In algebra, the smallest number is called negative infinity. In the .NET Framework, the negative infinity is represented by a constant named NegativeInfinity. To access this number, type either float or double, followed by a period operator, followed by the name of this constant.

To let you find out whether a variable holds a negative infinity value, the structures of the floating-point numbers are equipped with a method named IsNegativeInfinity. The syntaxes of this method are:

public static bool IsNegativeInfinity(float f);
public static bool IsNegativeInfinity(double d);

The Positive Infinity

On the other extreme, the possible largest number is named positive infinity. This constant is represented in the .NET Framework by the PositiveInfinity value. To access this constant, type float or double, followed by the period, followed by the name of this constant. To find out if a variable's value is a positive infinity, you can call its IsPositiveInfinity() method. The syntaxes of this method are:

public static bool IsPositiveInfinity(float f);
public static bool IsPositiveInfinity(double d);

To check whether the value of a variable is one of the infinities, you can call its IsInfinity() method. The syntaxes of this method are:

public static bool IsInfinity(float f);
public static bool IsInfinity(double d);

Comparison Operations

Because floating-point numbers can be approximate, you should be careful when comparing them, especially for equality. In face, you should avoid comparing them for equality.

Besides the equality, you can also compare floating-point variables to find out if one has a value lower than the other. To support such operations, the Single and the Double structures are equipped with a method named CompareTo. The rules of this method are functionally the same as those we reviewed for integers.

A Summary of .NET Data Types

All of the data types we have used so far are represented by structures in the .NET Framework. As a result, they are equipped with methods. These structures are defined in the System namespace. The structures of these data types are defined as:

C# Data Type Equivalent .NET Class
float Single
double Double
decimal Decimal

As a result, you can use the equivalent structure of a data type to declare a variable. Here are examples:

class Operations
{
    public double Addition()
    {
    	Double a;
        Double b;
        Double c;
		
        a = 128.76;
        b = 5044.52;
        c = a + b;

        return c;
    }
}

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2019, FunctionX Next