Saturday, July 5, 2014

05 - Numbers

There are no differences between integers and floats in JavaScript. All numeric values are represented in 64-bit floats.

var intValue = 2;
var floatValue = 3.6;

console.log(typeof(intValue)); // number
console.log(typeof(floatValue)); // number

As demonstrated in the code above, both the integer value 2 and the float value 3.6 are in the type of number.

Numbers in JavaScript can be large as ±1.7976931348623157×10^308 (Number.MAX_VALUE), and as little as ±5 × 10^324 (Number.MIN_VALUE). Since number values are in a very wide range, it is not necessary to handle the big-data issue specially in most cases.

var bigNumber = Math.pow(2, 100);
console.log(bigNumber); // 1.2676506002282294e+30

It is quite easy to calculate big values without considering the overflow issue. As shown in the code above, it calculates 2 to the power of 100 in a line of code.

When overflow occurs, there are no errors thrown. The code with overflow executes normally, and returns predefined values. The following is an example:

    var tooBig = Math.pow(10, 400);
    console.log("Finish without error. The returned value is:", tooBig);
    console.log("A error was caught.");

// Output:
// Finish without error. The returned value is: Infinity

When overflow occurs, the predefined special value Infinity is returned if the result is positive. Similarly, it returns -Infinity when overflow occurs with a negative result.

Moreover, no errors will be thrown when a number is divided by 0, as shown below:

var result1 = 1 / 0;
var result2 = -1 / 0;

console.log(result1); // Infinity
console.log(result2); // -Infinity

Another special value NaN (No a Number) is returned when 0 is divided by 0, or non-numeric values are calculated:

var result1 = 0 / 0;
console.log(result1); // NaN

var result2 = 5 / "hello";
console.log(result2); // NaN

No comments :

Post a Comment