JavaScript DHTML/Language Basics/Number Data Type

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

Add characters

   <source lang="html4strict">

<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;">

Please enter up to 15 letters (words, phrases, etc): <input name="myInput" onkeyup="checkLength()"> <input type="submit" value="Calculate!" name="submit">


       If a=1, b=2, c=3, etc, then your letters add up to:
<input name="myResult">

</form> </body> </html>



 </source>
   
  


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

   <source lang="html4strict">

<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">

<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 numbers is " + addThreeNums(theForm.num1.value,theForm.num2.value,theForm.num3.value, theForm.num4.value));">

</FORM> </BODY> </HTML>


 </source>
   
  


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

   <source lang="html4strict">

/* 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>


 </source>
   
  


Automatic Conversion between Types

   <source lang="html4strict">

<HTML> <HEAD> <TITLE>Implicit conversion between types</TITLE> <SCRIPT LANGUAGE="JavaScript">

</SCRIPT> </HEAD> <BODY>

Implicit conversion between types

<SCRIPT LANGUAGE="JavaScript"> </SCRIPT>

</BODY> </HTML>


 </source>
   
  


Complex class to represent complex numbers

   <source lang="html4strict">

/* 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);


 </source>
   
  


Concatenate integer variable to a string variable

   <source lang="html4strict">

<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>

 </source>
   
  


Concatenating Variables and Displaying the Value Contained

   <source lang="html4strict">

<HTML> <BODY> <SCRIPT>

  var trekVerb = "Make "; 
  var trekObject; 
  trekObject = "it so!"; 
  var trekQuote = trekVerb + trekObject; 
  document.write(trekQuote); 

</SCRIPT> </BODY> </HTML>


 </source>
   
  


Conversion of Logical Values to Numeric Values

   <source lang="html4strict">

<HTML> <HEAD> <TITLE>Conversion of logical values to numeric values</TITLE> </HEAD> <BODY> <SCRIPT LANGUAGE="JavaScript">

</SCRIPT> </BODY> </HTML>


 </source>
   
  


Converting a Number to a String

   <source lang="html4strict">

<html> <body> <script type="text/javascript">

</script> </body> </body>


 </source>
   
  


Converting Base 10 to Base 16 Using Bitwise Operators

   <source lang="html4strict">

/* 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">
 
 </script>

</body> </html>


 </source>
   
  


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

   <source lang="html4strict">

<html> <head>

 <script language="JavaScript1.1" type="text/javascript">
 
 </script>

</head> <body>

 <script language="JavaScript1.1" type="text/javascript">
 
 </script>

</body> </html>


 </source>
   
  


Date Object Calculations

   <source lang="html4strict">

<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>
Next week will be: <SCRIPT LANGUAGE="JavaScript"> document.write(nextWeek()); </SCRIPT> </BODY> </HTML>


 </source>
   
  


Decimal to 2 Hex

   <source lang="html4strict">

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;
   }

}


 </source>
   
  


Define variables, assign values and output

   <source lang="html4strict">

<HTML> <BODY> <SCRIPT language="JavaScript">

</SCRIPT> </BODY> </HTML>


 </source>
   
  


Dividing by Zero

   <source lang="html4strict">

<HTML> <HEAD> <TITLE>Dividing by Zero </TITLE> </HEAD> <BODY>

<SCRIPT> var theNum = new Number(42 / 0); var theStr = theNum.toString(); document.write(theStr); </SCRIPT>

</BODY> </HTML>


 </source>
   
  


Explicit Conversion Functions

   <source lang="html4strict">

<HTML> <HEAD> <TITLE>Using Explicit Conversion Functions</TITLE> </HEAD> <BODY>

Using Explicit Conversion Functions

<SCRIPT LANGUAGE="JavaScript"></SCRIPT> </BODY> </HTML>


 </source>
   
  


Factorials

   <source lang="html4strict">

/* 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("

Table of Factorials

");

for(i = 1, fact = 1; i < 10; i++, fact *= i) {

   document.write(i + "! = " + fact);
   document.write("
");

} </script> </body> </html>


 </source>
   
  


Format a number

   <source lang="html4strict">

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);


 </source>
   
  


Format a number 2

   <source lang="html4strict">

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";
   }

}


 </source>
   
  


JavaScript Loan Calculator

   <source lang="html4strict">

/* 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">

<form name="loandata">

Enter Loan Information:
1) Amount of the loan (any currency): <input type="text" name="principal" size="12" onchange="calculate();">
2) Annual percentage rate of interest: <input type="text" name="interest" size="12" onchange="calculate();">
3) Repayment period in years: <input type="text" name="years" size="12" onchange="calculate();">
     <input type="button" value="Compute" onclick="calculate();">
     Payment Information:
4) Your monthly payment will be: <input type="text" name="payment" size="12">
5) Your total payment will be: <input type="text" name="total" size="12">
6) Your total interest payments will be: <input type="text" name="totalinterest" size="12">

</form>

<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>


 </source>
   
  


Number Calculation

   <source lang="html4strict">

<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>

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


 </source>
   
  


Operator Precedence and Different Data Types

   <source lang="html4strict">

<html> <head>

 <title>Operator Precedence and Different Data Types</title>

</head> <body>

 <script type="text/javascript">
 
 </script></body>

</html>


 </source>
   
  


Using Floating-Point Numbers

   <source lang="html4strict">

<HTML> <HEAD> <TITLE>Using floating-point numbers</TITLE> </HEAD> <BODY> <SCRIPT LANGUAGE="JavaScript">

</SCRIPT> </BODY> </HTML>


 </source>
   
  


Using JavaScript Integers

   <source lang="html4strict">

<HTML> <HEAD> <TITLE>Using JavaScript integers</TITLE> </HEAD> <BODY> <SCRIPT LANGUAGE="JavaScript">

</SCRIPT> </BODY> </HTML>


 </source>
   
  


Using toString() with Radix Values

   <source lang="html4strict">

<HTML> <HEAD> <TITLE>Number Conversion Table</TITLE> </HEAD> <BODY> Using toString() to convert to other number bases:


<SCRIPT LANGUAGE="JavaScript"> var content = ""; for (var i = 0; i <= 20; i++) {

content += "" content += "" content += "" content += ""

} document.write(content) </SCRIPT>

DecimalHexadecimalBinary
" + i.toString(10) + "" + i.toString(16) + "" + i.toString(2) + "

</BODY> </HTML>


</source>