arrow_back
Back

JavaScript Number: integers, floats, and Math

Andrew Dorokhov Andrew Dorokhov schedule 1 min read
menu_book Table of Contents

Examples:

let number = 10;
let number = 1.4;

Additional data types:

  • Infinity and -Infinity.
  • NaN (not a number).

Working with math:

Math.round();
Math.floor(); // Round down to the nearest integer (drops the fractional part).

Random numbers

Math.random() returns a floating-point number in the range [0, 1) — always less than 1, never exactly 1:

Math.random();

Scale the range by multiplying. Example — a number from 0 to 10 (not including 10):

Math.random() * 10;

For an integer index into an array of length n, multiply by n and floor:

Math.floor(Math.random() * 4); // 0, 1, 2, or 3
Math.floor(Math.random() * arr.length);

Useful functions:

const number = parseInt(someString);
const number = parseFloat(someString);
const thisIsNotANumber = isNaN(someVariable);

Tricks

Convert string to number:

const s = '5';
const number = +s;
// or:
const number = +'5';

Conversion to a number

Number('15');   // We will get a number type.
+'15';          // We will get a number type.
code

Need Help with Development?

Happy to help — reach out via the contacts or go straight to my Upwork profile.

work View Upwork Profile arrow_forward
Next Article

JavaScript Boolean and truthy vs falsy values

arrow_forward