HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Numbers

JavaScript has only one type of number. Numbers can be written with or without decimals. Unlike many other programming languages, JavaScript does not define different types of numbers like integers, short, long, or floating-point.


Writing Numbers

Numbers in JavaScript can be written in several ways:

let x = 3.14;    // A number with decimals
let y = 3;       // A number without decimals
let z = 123e5;   // 12300000
let w = 123e-5;  // 0.00123

Floating Point Precision

Integers (numbers without a period) are accurate up to 15 digits. However, floating-point arithmetic is not always 100% accurate.

let x = 0.1 + 0.2;
console.log(x); // Result: 0.30000000000000004
Tip: To fix the precision issue, it helps to multiply the numbers to make them integers, perform the math, and then divide them back.

Adding Numbers and Strings

WARNING: JavaScript uses the + operator for both addition and concatenation.

  • If you add two numbers, the result will be a number.
  • If you add two strings, the result will be a string (concatenation).
  • If you add a number and a string, the result will be a string.
let x = 10;
let y = "20";
let result = x + y; // "1020" (concatenation)

NaN - Not a Number

NaN is a JavaScript reserved word indicating that a number is not a legal number. Trying to do arithmetic with a non-numeric string will result in NaN.

let x = 100 / "Apple";
console.log(x); // NaN

You can use the global isNaN() function to check if a value is not a number.


Infinity

Infinity (or -Infinity) is the value JavaScript returns if you calculate a number outside the largest possible number allowed.

let x = 2 / 0;       // Infinity
let y = -2 / 0;      // -Infinity
console.log(typeof Infinity); // "number"

Key Points to Remember

  • JavaScript has only one numeric type (64-bit float)
  • Floating point math is not always perfectly accurate
  • Adding a string to a number results in a string
  • NaN is used to represent an "illegal" number result
  • Infinity is a number that occurs when dividing by zero
  • Use typeof to verify that a value is numeric