Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > Ajax and JavaScript

  • Print
  • + Share This
This chapter is from the book

Working with Numbers

Unlike a lot of languages, JavaScript only has a single number type, used to represent any numerical value, from integers to doubles (i.e., decimals or real numbers) to exponent notation. You can rest assured in knowing that numbers in JavaScript can safely represent values up to around 9 quadrillion!

Let’s look at everything you need to know about numbers in JavaScript, from the arithmetic operators to formatting numbers, to using the Math object for more sophisticated purposes.

Arithmetic Operators

You’ve already been introduced to one operator: a single equals sign, which is the assignment operator. JavaScript supports the standard arithmetic operators, too (Table 4.1).

Table 4.1. Arithmetic Operators

SYMBOL

MEANING

+

Addition

-

Subtraction

*

Multiplication

/

Division

%

Remainder

The modulus operator, in case you’re not familiar with it, returns the remainder of a division. For example:

var remainder = 7 % 2; // 1;

One has to be careful when applying the modulus operator to negative numbers, as the remainder itself will also be negative:

var remainder = -7 % 2; // -1

These arithmetic operators can be combined with the assignment operator to both perform a calculation and assign the result in one step:

var cost = 50; // Dollars

cost *= 0.7373; // Converted to euros

You’ll frequently come across the increment and decrement operators: ++ and --. The increment operator adds one to the value of the variable; the decrement operator subtracts one:

var num = 1;

num++; // 2

num--; // 1

These two operators can be used in both prefix and postfix manners (i.e., before the variable or after it):

var num = 1;

num++; // num now equals 2.

++num; // num is now 3.

--num; // num is now 2.

A difference between the postfix and prefix versions is a matter of operator precedence. The rules of operator precedence dictate the order operations are executed in a multi-operation line. For example, basic math teaches that multiplication and division have a higher precedence than addition and subtraction. Thus:

var num = 3 * 2 + 1; // 7, not 9

Table 4.2 lists the order of precedence in JavaScript, from highest to lowest, including some operators not yet introduced (I’ve also omitted a couple of operators that won’t be discussed in this book). There’s also an issue of associativity that I’ve omitted, as that would be just one more thing you’d have to memorize. In fact, instead of trying to memorize that table, I recommend you use parentheses to force, or just clarify, precedence, without relying upon mastery of these rules. For example:

var num = (3 * 2) + 1; // Still 7.

That syntax, while two characters longer than the earlier version, has the same net effect but is easier to read and undeniably clear in intent.

Some of the operators in Table 4.2 are unary, meaning they apply to only one operand (such as ++ and --); others are binary, applying to two operands (such as addition). In Chapter 5, you’ll learn how to use the one trinary operator, which has three operands.

Table 4.2. Operator Precedence

PRECEDENCE

OPERATOR

NOTE

1

. []

member operators

1

new

creates new objects

2

()

function call

3

++ --

increment and decrement

4

!

logical not

4

+ -

unary positive and negative

4

typeof void delete

5

* / %

multiplication, division, and modulus

6

+ -

addition and subtraction

8

< <= > >=

comparison

9

== != === !==

equality

13

&&

logical and

14

||

logical or

15

?:

conditional operator

16

= += -= *= /= %= <<= >>= >>>= &= ^= |=

assignment operators

The last thing to know about performing arithmetic in JavaScript is if the result of the arithmetic is invalid, JavaScript will return one of two special values:

  • NaN, short for Not a Number
  • Infinity

For example, you’ll get these results if you attempt to perform arithmetic using strings or when you divide a number by zero, which surprisingly doesn’t create an error (Figure 4.2). In Chapter 5, you’ll learn how to use the isNaN() and isFinite() functions to verify that values are numbers safe to use as such.

Figure 4.2.

Figure 4.2. The result of invalid mathematical operations will be the special values NaN and Infinity.

Creating Calculators

At this point in time, you have enough knowledge to begin using JavaScript to perform real-world mathematical calculations, such as the kinds of things you’d put on a Web site:

  • Mortgage and similar loan calculators
  • Temperature and other unit conversions
  • Interest or investment calculators

For this particular example, let’s create an e-commerce tool that will calculate the total of an order, including tax, and minus any discount (Figure 4.3). The most relevant HTML is:

<div><label for="quantity">Quantity</label><input type="number"
 name="quantity" id="quantity" value="1" min="1" required></div>

<div><label for="price">Price Per Unit</label><input type="text"
 name="price" id="price" value="1.00" required></div>

<div><label for="tax">Tax Rate (%)</label><input type="text"
 name="tax" id="tax" value="0.0" required></div>

<div><label for="discount">Discount</label><input type="text"
 name="discount" id="discount" value="0.00" required></div>

<div><label for="total">Total</label><input type="text"
 name="total" id="total" value="0.00"></div>

<div><input type="submit" value="Calculate" id="submit"></div>
Figure 4.3.

Figure 4.3. A simple calculator.

That would go in a page named shopping.html, which includes the shopping.js JavaScript file, to be written in subsequent steps. You’ll notice that the HTML form makes use of the HTML5 number input type for the quantity, with a minimum value. The other types are simply text, as the number type doesn’t deal well with decimals. Each input is given a default value, and set as required. Remember that as Chapter 2, JavaScript in Action, explains, browsers that don’t support HTML5 will treat unknown types as text elements and ignore the unknown properties. The final text element will be updated with the results of the calculation.

To create a calculator:

  1. Create a new JavaScript file in your text editor or IDE, to be named shopping.js.
  2. Begin defining the calculate() function:
    function calculate() {
    
    'use strict';

    This function will be called when the user clicks the submit button. It does the actual work.

  3. Declare a variable for storing the order total:
    var total;

    As mentioned previously, you should generally declare variables as soon as you can, such as the first line of a function definition. Here, a variable named total is declared but not initialized.

  4. Get references to the form values:
    var quantity = document.getElementById('quantity').value;
    
    var price = document.getElementById('price').value;
    
    var tax = document.getElementById('tax').value;
    
    var discount = document.getElementById('discount').value;

    In these four lines of code, the values of the various form elements are assigned to local variables. Note that in the Chapter 2 example, variables were assigned references to the form elements, and then the element values were later checked. Here, the value is directly assigned to the variable.

    At this point in time, one would also perform validation of these values, prior to doing any calculations. But as Chapter 5 more formally covers the knowledge needed to perform validation, I’m skipping this otherwise needed step in this example.

  5. Calculate the initial total:
    total = quantity * price;

    The total variable is first assigned the value of the quantity times the price, using the multiplication operator.

  6. Factor in the tax rate:
    tax /= 100;
    
    tax++;
    
    total *= tax;

    There are a couple of ways one can calculate and add in the tax. The first, shown here, is to change the tax rate from a percent (say 5.25%) to a decimal (0.0525). Next, add one to the decimal (1.0525). Finally, multiply this number times the total. You’ll see that the division-assignment, incrementation, and multiplication-assignment operators are used here as shorthand. This code could also be written more formally:

    tax = tax/100;
    
    tax = tax + 1;
    
    total = total * tax;

    You could also make use of precedence and parentheses to perform all these calculations in one line.

    An alternative way to calculate the tax would be to convert it to decimal, multiply that value times the total, and then add that result to the total.

  7. Factor in the discount:
    total -= discount;

    The discount is just being subtracted from the total.

  8. Display the total in the form:
    document.getElementById('total').value = total;

    The value attribute can also be used to assign a value to a text form input. Using this approach, you can easily reflect data back to the user. In later chapters, you’ll learn how to display information on the HTML page using DOM manipulation, rather than setting the values of form inputs.

  9. Return false to prevent submission of the form:
    return false;

    The function must return a value of false to prevent the form from actually being submitted (to the page named by the form’s action attribute).

  10. Complete the function:
    } // End of calculate() function.
  11. Define the init() function:
    function init() {
    
       'use strict';
       var theForm = document.getElementById('theForm');
       theForm.onsubmit = calculate;
    
    } // End of init() function.

    The init() function will be called when the window triggers a load event (see Step 12). The function needs to add an event listener to the form’s submission, so that when the form is submitted, the calculate() function will be called. To do that, the function gets a reference to the form, by calling the document object’s getElementById() method, providing it with the unique ID value of the form. Then the variable’s onsubmit property is assigned the value calculate, as explained in Chapter 2.

  12. Add an event listener to the window’s load event:
    window.onload = init;

    This code was also explained in Chapter 2. It says that when the window has loaded, the init() function should be called.

    It’s a minor point, as you can organize your scripts in rather flexible ways, but this line is last as it references the init() function, defined in Step 12, so that definition should theoretically come before this line. That function references calculate(), so the calculate() function’s definition is placed before the init() function definition. You don’t have to organize your code this way, but I prefer to.

  13. Save the file as shopping.js, in a js directory next to shopping.html, and test in your Web browser (Figure 4.4).
    Figure 4.4.

    Figure 4.4. The result of the total order calculation.

    Play with the numbers, including invalid values (Figure 4.5), and retest the calculator until you’re comfortable with how arithmetic works in JavaScript.

    Figure 4.5.

    Figure 4.5. Performing arithmetic with invalid values, such as a quantity of cat, will result in a total of NaN.

Formatting Numbers

Although the previous example is perfectly useful, and certainly a good start, there are several ways in which it can be improved. For example, as written, no checks are made to ensure that the user enters values in all the form elements, let alone that those values are numeric (Figure 4.5) or, more precisely, positive numbers. That knowledge will be taught in the next chapter, which discusses conditionals, comparison operators, and so forth. Another problem, which can be addressed here, is that you can’t expect someone to pay, say, 22.1336999 (Figure 4.4). To improve the professionalism of the calculator, formatting the calculated total to two decimal points would be best.

A number in JavaScript is not just a number, but is also an object of type Number. As an object, a number has built-in methods, such as toFixed(). This method returns a number with a set number of digits to the right of a decimal point:

var num = 4095.3892;

num.toFixed(3); // 4095.389

Note that this method only returns the formatted number; it does not change the original value. To do that, you’d need to assign the result back to the variable, thereby replacing its original value:

num = num.toFixed(3);

If you don’t provide an argument to the toFixed() method, it defaults to 0:

var num = 4095.3892;

num.toFixed(3); // 4095

The method can round up to 20 digits.

Similar to toFixed() is toPrecision(). It takes an argument dictating the total number of significant digits, which may or may not include those after the decimal.

Let’s apply this information to the calculator in order to add some better formatting to the total.

To format a number:

  1. Open shopping.js in your text editor or IDE, if it is not already.
  2. After factoring in the discount, but before showing the total amount, format the total to two decimals:
    total = total.toFixed(2);

    This one line will take care of formatting the decimal places. Remember that the returned result must be assigned back to the variable in order for it to be represented upon later uses.

    Alternatively, you could just call total.toFixed(2) when assigning the value to the total form element.

  3. Save the file, reload the HTML page, and test it in your Web browser (Figure 4.6).
    Figure 4.5.

    Figure 4.6. The same input as in Figure 4.4 now generates a more appropriate result.

An even better way of formatting the number would be to add commands indicating thousands, but that requires more logic than can be understood at this point in the book.

The Math Object

You just saw that numbers in JavaScript can also be treated as objects of type Number, with a couple of built-in methods that can be used to manipulate them. Another way to manipulate numbers in JavaScript involves the Math object. Unlike Number, you do not create a variable of type Math, but use the Math object directly. The Math object is a global object in JavaScript, meaning it’s always available for you to use.

The Math object has several predefined constants, such as π, which is 3.14... and E, which is 2.71... A constant, unlike a variable, has a fixed value. Conventionally, constants are written in all uppercase letters, as shown. Referencing an object’s constant uses the same dot syntax as you would to reference one of its methods: Math.PI, Math.E, and so forth. Therefore, to calculate the area of a circle, you could use (Figure 4.7):

var radius = 20;

var area = Math.PI * radius * radius;
Figure 4.7.

Figure 4.7. The area of a circle, πr2, is calculated using the Math.PI constant.

The Math object also has several predefined methods, just a few of which are:

  • abs(), which returns the absolute value of a number
  • ceil(), which rounds up to the nearest integer
  • floor(), which rounds down to the nearest integer
  • max(), which returns the largest of zero or more numbers
  • min(), which returns the smallest of zero or more numbers
  • pow(), which returns one number to the power of another number
  • round(), which returns a number rounded to the nearest integer
  • random(), which returns a pseudo-random number between 0 (inclusive) and 1 (exclusive)

There are also several trigonometric methods like sin() and cos().

Another way of writing the formula for determining the area of a circle is:

var radius = 20;

var area = Math.PI * Math.pow(radius, 2);

To apply this new information, let’s create a new calculator that calculates the volume of a sphere, based upon a user-entered radius. That formula is:

volume = 4/3 * π * radius 3

Besides using the π constant and the pow() method, this next bit of JavaScript will also apply the abs() method to ensure that only a positive radius is used for the calculation (Figure 4.8). The relevant HTML is:

<div><label for="radius">Radius</label><input type="text" name="radius" id="radius" required></div>

<div><label for="volume">Volume</label><input type="text" name="volume" id="volume"></div>

<div><input type="submit" value="Calculate" id="submit"></div>
Figure 4.8.

Figure 4.8. This calculator determines and displays the volume of a sphere given a specific radius.

The HTML page includes the sphere.js JavaScript file, to be written in subsequent steps.

To calculate the volume of a sphere:

  1. Create a new JavaScript file in your text editor or IDE, to be named sphere.js.
  2. Begin defining the calculate() function:
    function calculate() {
    
    'use strict';
    
    var volume;

    Within the function, a variable named volume is declared, but not initialized.

  3. Get a reference to the form’s radius value:
    var radius = document.getElementById('radius').value;

    Again, this code closely replicates that in shopping.js, although there’s only one form value to retrieve.

  4. Make sure that the radius is a positive number:
    radius = Math.abs(radius);

    Applying the abs() method of the Math object to a number guarantees a positive number without having to use a conditional to test for that.

  5. Calculate the volume:
    volume = (4/3) * Math.PI * Math.pow(radius, 3);

    The volume of a sphere is four-thirds times π times the radius to the third power. This one line performs that entire calculation, using the Math object twice. The division of four by three is wrapped in parentheses to clarify the formula, although in this case the result would be the same without the parentheses.

  6. Format the volume to four decimals:
    volume = volume.toFixed(4);

    Remember that the toFixed() method is part of Number, which means it’s called from the volume variable, not from the Math object.

  7. Display the volume:
    document.getElementById('volume').value = volume;

    This code is the same as in the previous example, but obviously referencing a different form element.

  8. Return false to prevent the form’s submission, and complete the function:
        return false;
    
    } // End of calculate() function.
  9. Add an event listener to the form:
    function init() {
    
       'use strict';
       document.getElementById('calcForm').onsubmit = calculate;
    } // End of init() function.
    
    window.onload = init;

    This is the same code used in shopping.js. As in that example, when the form is submitted, the calculate() function will be called.

  10. Save the file as sphere.js, in a js directory next to sphere.html, and test it in your Web browser.
  • + Share This
  • 🔖 Save To Your Account

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit 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 Peachpit 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 ask@peachpit.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 Adobe Press. 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.peachpit.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