๐ŸŽ“ A1Learner
๐Ÿ”

JavaScript Number Methods

Number methods are built-in tools that work on number values. They turn numbers into text, round them, and read numbers back out of text.

Numbers as text

The toString method turns a number into text. The typeof check proves the change.

let score = 42;
let label = score.toString();
console.log(label);
console.log(typeof label);

Rounding with toFixed

The toFixed method rounds to the count of decimals in its parentheses. The result is text, and typeof proves it.

let price = 3.14159;
let rounded = price.toFixed(2);
console.log(rounded);
console.log(typeof rounded);

Reading numbers from text

parseInt stops at letters, and parseFloat keeps the decimals. The last line shows the type that Number produces.

console.log(parseInt("42px"));
console.log(parseFloat("3.5kg"));
console.log(typeof Number("42"));

Example

let raw = "19.99";
let price = parseFloat(raw);
let total = price.toFixed(2);
console.log(total);
console.log(typeof total);
let count = Number("3");
console.log(count + 1);

Key points

  • Each number method takes a number and returns a new value.
  • Number("42") converts the text "42" into the number 42.
  • parseInt reads a whole number from the start of a piece of text.
  • parseFloat reads a decimal number from the start of a piece of text.
  • Number.isInteger reports true for a whole number and false for a decimal.

In this example, parseFloat reads the decimal 19.99 from the text. toFixed formats that price with two decimals, and typeof shows the result is a string. Number then converts the text "3" into a number, so adding 1 prints 4.

Try it Yourself

Edit the code, then press Run.

Runs in your browser โ€” the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What does (7).toFixed(1) return?