JavaScript DHTML/Language Basics/Number Data Type

Материал из Web эксперт
Перейти к: навигация, поиск

Add characters

 

<html>
<head>
<title>add characters test</title>
<script language="JavaScript">
function myCalc(){
  var myLetters = new Array(" ", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", 
                            "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", 
                            "v", "w", "x", "y", "z");
  var myNumbers = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 
                            16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26);
  var myPreAddends = document.myForm.myInput.value;
  var myLowerCase = myPreAddends.toLowerCase();
  var mySum = 0
  for(i=0; i<myLowerCase.length; i++) {
  myAddend = myLowerCase.charAt(i);
  for (x=0; x<myLetters.length; x++) {
    if (myAddend == myLetters[x]) {
    myAddend = myNumbers[x];
    }
  }
  mySum=mySum + myAddend
  
  }
  document.myForm.myResult.value = mySum;
}
function checkLength() {
  var InputCheck = document.myForm.myInput.value
  if (InputCheck.length > 15) {
  alert("Only 15 characters please!");
  }
}
</script>

</head>
<body>
<form name="myForm" onsubmit="myCalc(); return false;">
    <p>Please enter up to 15 letters (words, phrases, etc):
    
    <input name="myInput" onkeyup="checkLength()">
    <input type="submit" value="Calculate!" name="submit">
    <hr>
        If a=1, b=2, c=3, etc, then your letters add up to:<br>
    <input name="myResult">
</form>
</body>
</html>



Add Four Numbers from an HTML Form (and Display the Results)

 
<HTML>
<HEAD>
<TITLE>Add all of the numbers </TITLE>
<SCRIPT> 
   function addNums () { 
      var theAnswer = 0; 
      for (var i = 0; i < addNums.arguments.length; i++) { 
         var theNum = Number(addNums.arguments[i]); 
         theAnswer += theNum; 
      } 
      return theAnswer; 
   } 
   </SCRIPT>
</HEAD>
<BODY>
<FORM Name="theForm">
<TABLE cellspacing=5>
<TR>
<TD>
<INPUT Type=Text Name="num1">
</TD>
<TD>
<INPUT Type=Text Name="num2">
</TD>
<TD>
<INPUT Type=Text Name="num3">
</TD>
</TR>
<TR>
<TD>
</TD>
<TD>
</TD>
<TD align=right>
<INPUT Type=Button Value="Add Them" onClick="document.write("The sum of the numbers is " + 
addThreeNums(theForm.num1.value,theForm.num2.value,theForm.num3.value, theForm.num4.value));">
</TD>
</TR>
</TABLE>
</FORM>
</BODY>
</HTML>



A Function That Returns the Sum of Three Numbers (Stripped-Down Version)

 
/*
Learn How to Program Using Any Web Browser
by Harold Davis 
Apress CopyRight 2004
ISBN: 1590591135
*/
<HTML>
<HEAD>
<TITLE> 
   Add three numbers 
   </TITLE>
<SCRIPT> 
   function addThreeNums (inOne, inTwo, inThree) { 
      var inOne = Number(inOne); 
      var inTwo = Number(inTwo); 
      var inThree = Number(inThree); 
      return Number(inOne + inTwo + inThree); 
   } 
   </SCRIPT>
</HEAD>
<BODY>
<FORM Name="theForm">
<INPUT Type=Text Name="num1">
<INPUT Type=Text Name="num2">
<INPUT Type=Text Name="num3">
<INPUT Type=Button Value="Add Them" 
         onClick="document.write("The sum of the three numbers is " + 
addThreeNums(theForm.num1.value,theForm.num2.value,theForm.num3.value));">
</FORM>
</BODY>
</HTML>



Automatic Conversion between Types

 
<HTML>
<HEAD>
<TITLE>Implicit conversion between types</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
s1="test"
s2="1122.34"
i=123
r=.123
lt=true
lf=false
n=null
// -->
</SCRIPT>
</HEAD>
<BODY>
<H1>Implicit conversion between types</H1>
<TABLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
document.write("<TR>")
document.write("<TH>row + column</TH>")
document.write("<TH>string \"12.34\"</TH>")
document.write("<TH>integer 123</TH>")
document.write("<TH>float .123</TH>")
document.write("<TH>logical true</TH>")
document.write("<TH>logical false</TH>")
document.write("<TH>null</TH>")
document.write("</TR>")
// First operand is a string
document.write("<TR>")
document.write("<TH>string \"test\"</TH>")
document.write("<TD>")
document.write(s1+s2)
document.write("</TD><TD>")
document.write(s1+i)
document.write("</TD><TD>")
document.write(s1+r)
document.write("</TD><TD>")
document.write(s1+lt)
document.write("</TD><TD>")
document.write(s1+lf)
document.write("</TD><TD>")
document.write(s1+n)
document.write("</TD>")
document.write("</TR>")
// First operand is an integer
document.write("<TR>")
document.write("<TH>integer 123</TH>")
document.write("<TD>")
document.write(i+s2)
document.write("</TD><TD>")
document.write(i+i)
document.write("</TD><TD>")
document.write(i+r)
document.write("</TD><TD>")
document.write(i+lt)
document.write("</TD><TD>")
document.write(i+lf)
document.write("</TD><TD>")
document.write(i+n)
document.write("</TD>")
document.write("</TR>")
// First operand is a float
document.write("<TR>")
document.write("<TH>float .123</TH>")
document.write("<TD>")
document.write(r+s2)
document.write("</TD><TD>")
document.write(r+i)
document.write("</TD><TD>")
document.write(r+r)
document.write("</TD><TD>")
document.write(r+lt)
document.write("</TD><TD>")
document.write(r+lf)
document.write("</TD><TD>")
document.write(r+n)
document.write("</TD>")
document.write("</TR>")
// First operand is a logical true
document.write("<TR>")
document.write("<TH>logical true</TH>")
document.write("<TD>")
document.write(lt+s2)
document.write("</TD><TD>")
document.write(lt+i)
document.write("</TD><TD>")
document.write(lt+r)
document.write("</TD><TD>")
document.write(lt+lt)
document.write("</TD><TD>")
document.write(lt+lf)
document.write("</TD><TD>")
document.write(lt+n)
document.write("</TD>")
document.write("</TR>")
// First operand is a logical false
document.write("<TR>")
document.write("<TH>logical false</TH>")
document.write("<TD>")
document.write(lf+s2)
document.write("</TD><TD>")
document.write(lf+i)
document.write("</TD><TD>")
document.write(lf+r)
document.write("</TD><TD>")
document.write(lf+lt)
document.write("</TD><TD>")
document.write(lf+lf)
document.write("</TD><TD>")
document.write(lf+n)
document.write("</TD>")
document.write("</TR>")
// First operand is null
document.write("<TR>")
document.write("<TH>null</TH>")
document.write("<TD>")
document.write(n+s2)
document.write("</TD><TD>")
document.write(n+i)
document.write("</TD><TD>")
document.write(n+r)
document.write("</TD><TD>")
document.write(n+lt)
document.write("</TD><TD>")
document.write(n+lf)
document.write("</TD><TD>")
document.write(n+n)
document.write("</TD>")
document.write("</TR>")
// -->
</SCRIPT>
</TABLE>
</BODY>
</HTML>



Complex class to represent complex numbers

 
/*
Examples From
JavaScript: The Definitive Guide, Fourth Edition
Legal matters: these files were created by David Flanagan, and are
Copyright (c) 2001 by David Flanagan.  You may use, study, modify, and
distribute them for any purpose.  Please note that these examples are
provided "as-is" and come with no warranty of any kind.
David Flanagan
*/
/*
 * Complex.js:
 * This file defines a Complex class to represent complex numbers.
 * Recall that a complex number is the sum of a real number and an
 * imaginary number, and that the imaginary number i is the
 * square root of -1.
 */
/*
 * The first step in defining a class is defining the constructor
 * function of the class. This constructor should initialize any
 * instance properties of the object. These are the essential
 * "state variables" that make each instance of the class different.
 */
function Complex(real, imaginary) {
    this.x = real;       // The real part of the number
    this.y = imaginary;  // The imaginary part of the number
}
/*
 * The second step in defining a class is defining its instance
 * methods (and possibly other properties) in the prototype object
 * of the constructor. Any properties defined in this object will
 * be inherited by all instances of the class. Note that instance
 * methods operate implicitly on the this keyword. For many methods,
 * no other arguments are needed.
 */
// Return the magnitude of a complex number. This is defined
// as its distance from the origin (0,0) of the complex plane.
Complex.prototype.magnitude = function() {
    return Math.sqrt(this.x*this.x + this.y*this.y);
};
// Return a complex number that is the negative of this one.
Complex.prototype.negative = function() {
    return new Complex(-this.x, -this.y);
};
// Convert a Complex object to a string in a useful way.
// This is invoked when a Complex object is used as a string.
Complex.prototype.toString = function() {
    return "{" + this.x + "," + this.y + "}";
};
// Return the real portion of a complex number. This function
// is invoked when a Complex object is treated as a primitive value.
Complex.prototype.valueOf = function() { return this.x; }
/*
 * The third step in defining a class is to define class methods,
 * constants, and any needed class properties as properties of the
 * constructor function itself (instead of as properties of the
 * prototype object of the constructor). Note that class methods
 * do not use the this keyword: they operate only on their arguments.
 */
// Add two complex numbers and return the result.
Complex.add = function (a, b) {
    return new Complex(a.x + b.x, a.y + b.y);
};
// Subtract one complex number from another.
Complex.subtract = function (a, b) {
    return new Complex(a.x - b.x, a.y - b.y);
};
// Multiply two complex numbers and return the product.
Complex.multiply = function(a, b) {
    return new Complex(a.x * b.x - a.y * b.y,
                       a.x * b.y + a.y * b.x);
};
// Here are some useful predefined complex numbers.
// They are defined as class properties, where they can be used as
// "constants." (Note, though, that they are not actually read-only.)
Complex.zero = new Complex(0,0);
Complex.one = new Complex(1,0);
Complex.i = new Complex(0,1);



Concatenate integer variable to a string variable

 
<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
var A = "10", B = 5; 
C = A + B;
alert(C);
</script>
</head>
<body>
</body>
</html>



Concatenating Variables and Displaying the Value Contained

 
<HTML>
<BODY>
<SCRIPT> 
   var trekVerb = "Make "; 
   var trekObject; 
   trekObject = "it so!"; 
   var trekQuote = trekVerb + trekObject; 
   document.write(trekQuote); 
</SCRIPT>
</BODY>
</HTML>



Conversion of Logical Values to Numeric Values

 
<HTML>
<HEAD>
<TITLE>Conversion of logical values to numeric values</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!--
document.write("true*5 + false*7 = ")
document.write(true*5 +false*7)
// -->
</SCRIPT>
</BODY>
</HTML>



Converting a Number to a String

 
<html>
<body>
<script type="text/javascript">
<!--
  function numToString(number) {
    number += "";
    return number;
  }
   
  var number = 10;
  alert(typeof number);
  number = numToString(number);
  alert(typeof number);
//-->
</script>
</body>
</body>



Converting Base 10 to Base 16 Using Bitwise Operators

 
/*
JavaScript Unleashed, Third Edition
by Richard Wagner and R. Allen Wyke 
ISBN: 067231763X
Publisher Sams CopyRight 2000
*/
<html>
<head>
  <title>JavaScript Unleashed</title>
</head>
<body>
  <script type="text/javascript">
  <!--
    // Declare variables
    var originalInt;
   
    // intValue can be any 8 bit value.    var intValue = 0xDC; 
    var controlValue = 0xF;
    var fourBitValue;
    var hexChar = "";
    var hexString = "";
   
    document.writeln("When displaying integers from memory,");
    document.writeln("JavaScript always uses their decimal ");
    document.writeln("equivalent: " + intValue);
    originalInt = intValue;
    fourBitValue =  controlValue & intValue;
    hexChar = (fourBitValue == 0x0) ? "0" : hexChar;
    hexChar = (fourBitValue == 0x1) ? "1" : hexChar;
    hexChar = (fourBitValue == 0x2) ? "2" : hexChar;
    hexChar = (fourBitValue == 0x3) ? "3" : hexChar;
    hexChar = (fourBitValue == 0x4) ? "4" : hexChar;
    hexChar = (fourBitValue == 0x5) ? "5" : hexChar;
    hexChar = (fourBitValue == 0x6) ? "6" : hexChar;
    hexChar = (fourBitValue == 0x7) ? "7" : hexChar;
    hexChar = (fourBitValue == 0x8) ? "8" : hexChar;
    hexChar = (fourBitValue == 0x9) ? "9" : hexChar;
    hexChar = (fourBitValue == 0xA) ? "A" : hexChar;
    hexChar = (fourBitValue == 0xB) ? "B" : hexChar;
    hexChar = (fourBitValue == 0xC) ? "C" : hexChar;
    hexChar = (fourBitValue == 0xD) ? "D" : hexChar;
    hexChar = (fourBitValue == 0xE) ? "E" : hexChar;
    hexChar = (fourBitValue == 0xF) ? "F" : hexChar;
   
    // Build hexString placing digits from right to left
    hexString = hexChar + hexString;
   
    // Shift intValue four bits right
    intValue = intValue >> 4;
   
    // Extract the next four bit value
    fourBitValue =  controlValue & intValue;
   
    // Find the matching hex value and assign its string
    // equivalent to hexChar.
    hexChar = (fourBitValue == 0x0) ? "0" : hexChar;
    hexChar = (fourBitValue == 0x1) ? "1" : hexChar;
    hexChar = (fourBitValue == 0x2) ? "2" : hexChar;
    hexChar = (fourBitValue == 0x3) ? "3" : hexChar;
    hexChar = (fourBitValue == 0x4) ? "4" : hexChar;
    hexChar = (fourBitValue == 0x5) ? "5" : hexChar;
    hexChar = (fourBitValue == 0x6) ? "6" : hexChar;
    hexChar = (fourBitValue == 0x7) ? "7" : hexChar;
    hexChar = (fourBitValue == 0x8) ? "8" : hexChar;
    hexChar = (fourBitValue == 0x9) ? "9" : hexChar;
    hexChar = (fourBitValue == 0xA) ? "A" : hexChar;
    hexChar = (fourBitValue == 0xB) ? "B" : hexChar;
    hexChar = (fourBitValue == 0xC) ? "C" : hexChar;
    hexChar = (fourBitValue == 0xD) ? "D" : hexChar;
    hexChar = (fourBitValue == 0xE) ? "E" : hexChar;
    hexChar = (fourBitValue == 0xF) ? "F" : hexChar;
    hexString = hexChar + hexString;
    document.write("<br>" + originalInt + " displayed in");
    document.write(" hexadecimal :");
    document.writeln(hexString);
    // end hiding -->
  </script>
</body>
</html>



Creating Number Objects Rather than Performing String-to-Number Conversions

 
<html>
<head>
  <script language="JavaScript1.1" type="text/javascript">
  <!--
    Number.prototype.description = null;
   
    Highway = new Number(65);
    City = new Number(35);
    SchoolZone = new Number(25);
   
    Highway.description = "Interstate Highway Speed Limit";
    City.description = "City Speed Limit";
    SchoolZone.description = "School Zone Speed Limit";
   
    function tellDifference(num1, num2) {
      diff = num1 - num2;
      document.write("The speed difference between " + num1.description +
                          " and " + num2.description + " is " + diff);    }
   
  //-->
  </script>
</head>
<body>
  <script language="JavaScript1.1" type="text/javascript">
  <!--
    // Call function
    tellDifference(Highway,  City);
  //-->
  </script>
</body>
</html>



Date Object Calculations

 
<HTML>
<HEAD>
<TITLE>Date Calculation</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function nextWeek() {
    var todayInMS = today.getTime()
    var nextWeekInMS = todayInMS + (60 * 60 * 24 * 7 * 1000)
    return new Date(nextWeekInMS)
}
</SCRIPT>
</HEAD>
<BODY>
Today is: 
<SCRIPT LANGUAGE="JavaScript">
var today = new Date();
document.write(today);
</SCRIPT>
<BR>
Next week will be:
<SCRIPT LANGUAGE="JavaScript">
document.write(nextWeek());
</SCRIPT>
</BODY>
</HTML>



Decimal to 2 Hex

 
<!-- 
     Example File From "JavaScript and DHTML Cookbook"
     Published by O"Reilly & Associates
     Copyright 2003 Danny Goodman
-->
function dec2Hex(dec) {
    dec = parseInt(dec, 10);
    if (!isNaN(dec)) {
        hexChars = "0123456789ABCDEF";
        if (dec > 255) {
            return "Out of Range";
        }
        var i = dec % 16;
        var j = (dec - i) / 16;
        result = "0x";
        result += hexChars.charAt(j) + hexChars.charAt(i);
        return result;
    } else {
        return NaN;
    }
}



Define variables, assign values and output

 
<HTML>
<BODY>
<SCRIPT language="JavaScript">
<!--
var paycheck=20;
document.write(paycheck+"<BR>");
paycheck+=2000;
document.write(paycheck+"<BR>");
paycheck=paycheck-500;
document.write(paycheck+"<BR>");
paycheck=paycheck*0;
document.write(paycheck+"<BR>");
paycheck=paycheck+500;
document.write(paycheck+"<BR>");
paycheck-=80;
document.write(paycheck+"<BR>");
//-->
</SCRIPT>
</BODY>
</HTML>



Dividing by Zero

 
<HTML>
<HEAD>
<TITLE>Dividing by Zero
</TITLE>
</HEAD>
<BODY>
<H1>
<SCRIPT> 
var theNum = new Number(42 / 0); 
var theStr = theNum.toString(); 
document.write(theStr); 
</SCRIPT>
</H1>
</BODY>
</HTML>



Explicit Conversion Functions

 
<HTML>
<HEAD>
<TITLE>Using Explicit Conversion Functions</TITLE>
</HEAD>
<BODY>
<H1 ALIGN="CENTER">Using Explicit Conversion Functions</H1>
<SCRIPT LANGUAGE="JavaScript"><!--
document.write("eval("12.34*10") = ")
document.write(eval("12.34*10"))
document.write("<BR>")
document.write("parseInt("0x10") = ")
document.write(parseInt("0x10"))
document.write("<BR>")
document.write("parseFloat("5.4321e6") = ")
document.write(parseFloat("5.4321e6"))
// --></SCRIPT>
</BODY>
</HTML>



Factorials

 
/*
Examples From
JavaScript: The Definitive Guide, Fourth Edition
Legal matters: these files were created by David Flanagan, and are
Copyright (c) 2001 by David Flanagan.  You may use, study, modify, and
distribute them for any purpose.  Please note that these examples are
provided "as-is" and come with no warranty of any kind.
David Flanagan
*/
<html>
<body>
<head><title>Factorials</title></head>
<script language="JavaScript">
document.write("<h2>Table of Factorials</h2>");
for(i = 1, fact = 1; i < 10; i++, fact *= i) {
    document.write(i + "! = " + fact);
    document.write("<br>");
}
</script>
</body>
</html>



Format a number

 
<!-- 
     Example File From "JavaScript and DHTML Cookbook"
     Published by O"Reilly & Associates
     Copyright 2003 Danny Goodman
-->
function formatNumber (num, decplaces) {
    // convert in case it arrives as a string value
    num = parseFloat(num);
    // make sure it passes conversion
    if (!isNaN(num)) {
        // multiply value by 10 to the decplaces power;
        // round the result to the nearest integer;
        // convert the result to a string
        var str = "" + Math.round (eval(num) * Math.pow(10,decplaces));
        // exponent means value is too big or small for this routine
        if (str.indexOf("e") != -1) {
            return "Out of Range";
        }
        // if needed for small values, pad zeros
        // to the left of the number
        while (str.length <= decplaces) {
            str = "0" + str;
        }
        // calculate decimal point position
        var decpoint = str.length - decplaces;
        // assemble final result from: (a) the string up to the position of
        // the decimal point; (b) the decimal point; and (c) the balance
        // of the string. Return finished product.
        return str.substring(0,decpoint) + "." + str.substring(decpoint,str.length);
    } else {
        return "NaN";
    }
}
document.myForm.total.value = formatNumber(someNumber, 2);



Format a number 2

 
<!-- 
     Example File From "JavaScript and DHTML Cookbook"
     Published by O"Reilly & Associates
     Copyright 2003 Danny Goodman
-->
function formatCommas(numString) {
    var re = /(-?\d+)(\d{3})/;
    while (re.test(numString)) {
        numString = numString.replace(re, "$1,$2");
    }
    return numString;
}
function formatNumber (num, decplaces) {
    // convert in case it arrives as a string value
    num = parseFloat(num);
    // make sure it passes conversion
    if (!isNaN(num)) {
        // multiply value by 10 to the decplaces power;
        // round the result to the nearest integer;
        // convert the result to a string
        var str = "" + Math.round (eval(num) * Math.pow(10,decplaces));
        // exponent means value is too big or small for this routine
        if (str.indexOf("e") != -1) {
            return "Out of Range";
        }
        // if needed for small values, pad zeros
        // to the left of the number
        while (str.length <= decplaces) {
            str = "0" + str;
        }
        // calculate decimal point position
        var decpoint = str.length - decplaces;
        // assemble final result from: (a) the string up to the position of
        // the decimal point; (b) the decimal point; and (c) the balance
        // of the string. Return finished product.
        return formatCommas(str.substring(0,decpoint)) + "." + str.substring(decpoint,str.length);
    } else {
        return "NaN";
    }
}



JavaScript Loan Calculator

 
/*
Examples From
JavaScript: The Definitive Guide, Fourth Edition
Legal matters: these files were created by David Flanagan, and are
Copyright (c) 2001 by David Flanagan.  You may use, study, modify, and
distribute them for any purpose.  Please note that these examples are
provided "as-is" and come with no warranty of any kind.
David Flanagan
*/
<head><title>JavaScript Loan Calculator</title></head>
<body bgcolor="white">
<!-- 
  This is an HTML form that allows the user to enter data, and allows
  JavaScript to display the results it computes back to the user. The
  form elements are embedded in a table to improve their appearance.
  The form itself is given the name "loandata", and the fields within
  the form are given names like "interest" and "years".  These
  fieldnames are used in the JavaScript code that follows the form.
  Note that some of the form elements define "onchange" or "onclick"
  event handlers. These specify strings of JavaScript code to be
  executed when the user enters data or clicks on a button. 
-->
<form name="loandata">
  <table>
    <tr><td colspan="3"><b>Enter Loan Information:</b></td></tr>
    <tr>
      <td>1)</td>
      <td>Amount of the loan (any currency):</td>
      <td><input type="text" name="principal" size="12" 
                 onchange="calculate();"></td>
    </tr>
    <tr>
      <td>2)</td>
      <td>Annual percentage rate of interest:</td>
      <td><input type="text" name="interest" size="12" 
                 onchange="calculate();"></td>
    </tr>
    <tr>
      <td>3)</td>
      <td>Repayment period in years:</td>
      <td><input type="text" name="years" size="12" 
                 onchange="calculate();"></td>
    </tr>
    <tr><td colspan="3">
      <input type="button" value="Compute" onclick="calculate();">
    </td></tr>
    <tr><td colspan="3">
      <b>Payment Information:</b>
    </td></tr>
    <tr>
      <td>4)</td>
      <td>Your monthly payment will be:</td>
      <td><input type="text" name="payment" size="12"></td>
    </tr>
    <tr>
      <td>5)</td>
      <td>Your total payment will be:</td>
      <td><input type="text" name="total" size="12"></td>
    </tr>
    <tr>
      <td>6)</td>
      <td>Your total interest payments will be:</td>
      <td><input type="text" name="totalinterest" size="12"></td>
    </tr>
  </table>
</form>
<!--
  This is the JavaScript program that makes the example work. Note that
  this script defines the calculate() function called by the event
  handlers in the form.  The function refers to values in the form
  fields using the names defined in the HTML code above.
-->
<script language="JavaScript">
function calculate() {
    // Get the user"s input from the form. Assume it is all valid.
    // Convert interest from a percentage to a decimal, and convert from
    // an annual rate to a monthly rate. Convert payment period in years
    // to the number of monthly payments.
    var principal = document.loandata.principal.value;
    var interest = document.loandata.interest.value / 100 / 12;
    var payments = document.loandata.years.value * 12;
    // Now compute the monthly payment figure, using esoteric math.
    var x = Math.pow(1 + interest, payments);
    var monthly = (principal*x*interest)/(x-1);
    // Check that the result is a finite number. If so, display the results
    if (!isNaN(monthly) && 
        (monthly != Number.POSITIVE_INFINITY) &&
        (monthly != Number.NEGATIVE_INFINITY)) {
        document.loandata.payment.value = round(monthly);
        document.loandata.total.value = round(monthly * payments);
        document.loandata.totalinterest.value = 
            round((monthly * payments) - principal);
    }
    // Otherwise, the user"s input was probably invalid, so don"t
    // display anything.
    else {
        document.loandata.payment.value = "";
        document.loandata.total.value = "";
        document.loandata.totalinterest.value = "";
    }
}
// This simple method rounds a number to two decimal places.
function round(x) {
  return Math.round(x*100)/100;
}
</script>
</body>
</html>



Number Calculation

 

<html>
<head>
<title>Prices Demo</title>
<script language="javascript">
function calculation() {
  var number= document.prices.quantity.value;
  total = "" + Math.round((number*12.95)*100)/100;
  if (total.indexOf(".") == -1) 
    total += ".00"; 
  else if (total.indexOf(".") == total.length-2) 
    total += "0"; 
  document.prices.subtotal.value = total += "$";
}
</script>

</head>
<body>
<form name="prices">
<select name="quantity" onClick="calculation()">
  <option value="0">0</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
  <option value="6">6</option>
  <option value="7">7</option>
  <option value="8">8</option>
  <option value="9">9</option>
  <option value="10">10</option>
</select>
<br>

<input type="text" name="subtotal" value="0.00$">
</form>
</body>
</html>



Operator Precedence and Different Data Types

 
<html>
<head>
  <title>Operator Precedence and Different Data Types</title>
</head>
<body>
  <script type="text/javascript">
  <!--
    var carLength = 4 + 5;
    document.write(carLength);
    carLength = "<br>" + 4 + 5 + " feet";
    document.write(carLength);
    carLength = "<br>Length in feet: " + 4 + 5;
    document.write(carLength);
    carLength = "<br>Length in feet: " + (4 + 5);
    document.writeln(carLength);
  //-->
  </script></body>
</html>



Using Floating-Point Numbers

 
<HTML>
<HEAD>
<TITLE>Using floating-point numbers</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!--
document.write(-4.321)
document.write("<BR>")
document.write(55.)
document.write("<BR>")
document.write(12e2)
document.write("<BR>")
document.write(1e-2)
document.write("<BR>")
document.write(7e1)
document.write("<BR>")
document.write(-4e-4)
document.write("<BR>")
document.write(.5)
// -->
</SCRIPT>
</BODY>
</HTML>



Using JavaScript Integers

 
<HTML>
<HEAD>
<TITLE>Using JavaScript integers</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!--
document.write("0xab00 + 0xcd = ")
document.write(0xab00 + 0xcd)
document.write("<BR>")
document.write("0xff - 0123 = ")
document.write(0xff - 0123)
document.write("<BR>")
document.write("-0x12 = ")
document.write(-0x12)
// -->
</SCRIPT>
</BODY>
</HTML>



Using toString() with Radix Values

 
<HTML>
<HEAD>
<TITLE>Number Conversion Table</TITLE>
</HEAD>
<BODY>
<B>Using toString() to convert to other number bases:</B>
<HR>
<TABLE>
<TR>
<TH>Decimal</TH><TH>Hexadecimal</TH><TH>Binary</TH></TR>
<SCRIPT LANGUAGE="JavaScript">
var content = "";
for (var i = 0; i <= 20; i++) {
    content += "<TR>"
    content += "<TD>" + i.toString(10) + "</TD>"
    content += "<TD>" + i.toString(16) + "</TD>"
    content += "<TD>" + i.toString(2) + "</TD></TR>"
}
document.write(content)
</SCRIPT>
</TABLE>
</BODY>
</HTML>