Use of numbers in javascript with examples.
Numbers in Javascript
Integers, decimals and numbers in scientific notation may be used in javascript. In the example below x is assigned 20 which is an integer , y is assigned 35.9 which is a decimal number and z is assigned 1.45×102, written as 1.45e2;, which is a number in scientific notation. Run the sample program below and explain the answer displayed as 200.9.
<!DOCTYPE html>
<html>
<body>
<script>
var x = 20;
var y = 35.9;
var z = 1.45e2;
var w = x + y + z;
alert(w);
</script>
</body>
</html>
Hexadecimal in Javascript
Javascript understand hexadecimal numbers when preceded by 0x (zero followed by x). In the example below, x is declared as a hexadecimal 2D because of the 0x. 2DF in decimal is equal to : 2×162 + D×161 + F×160 = 2×162 +13×161 + 15×160 = 735. The value of the variable x is the sum of 2DF converted into an integer (735) plus 100. Run the sample program and check that 835 is displayed.
<!DOCTYPE html>
<html>
<body>
<script>
var x = 0x2DF, y = 100;
alert(x+y);
</script>
</body>
</html>
Convert an Integer to Another Base
There is a method that you may use to convert from base 10 to another base. It has the form toString(b), where b is the base to convert to. In the example below, 255 is converted to base 16 (hexadecimal). Run and check the the answer is ff (= 15×161 + 15×160 = 255).
<!DOCTYPE html>
<html>
<body>
<script>
var x = 255;
var xHexadecimal = x.toString(16);
alert(xHexadecimal);
</script>
</body>
</html>
Books and References
1 - A Smarter Way to Learn JavaScript: The new approach that uses technology to cut your effort in half - Mark Myers
2 - JavaScript and JQuery: Interactive Front-End Web Development 1st Edition - Jon Duckett - ISBN-13: 978-1118531648
3 - A Smarter Way to Learn HTML & CSS: Learn it faster. Remember it longer. (Volume 2) - Mark Myers
4 - http://www.w3schools.com/js/default.asp - JavaScript Tutorial