bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch

Loading lesson path

Learn/JavaScript/Working with Data
JavaScript•Working with Data

JavaScript Number Methods

Concept visual

JavaScript Number Methods

Pointer walk
two pointers
leftright102132436485116
left=0
right=6
1
3

Start at both ends

Basic Methods

Basic number methods can be used on any number

toString() toExponential() toFixed() toPrecision() valueOf()

Static Methods

Static methods can only be used on Number

Number.isFinite() Number.isInteger() Number.isNan() Number.isSafeInteger() Number.parseInt() Number.parseFloat()

See Also:

Numbers Tutorial

Number Properties

Number Reference

The toString() Method

The toString()

method returns a number as a string. All number methods can be used on any type of numbers (literals, variables, or expressions):

Example

let x = 123;
x.toString();
(123).toString();
(100 + 23).toString();

The toString()

method can take an optional radix argument to convert the number to a different base:

Example

let x = 123;
let text = x.toString(2);
The toExponential() Method toExponential() returns a string, with a number rounded and written using exponential notation.

A parameter defines the number of characters behind the decimal point:

Example

let x = 9.656;
x.toExponential(2);
x.toExponential(4);
x.toExponential(6);

Try it Yourself » The parameter is optional. If you don't specify it, JavaScript will not round the number. The toFixed() Method toFixed() returns a string, with the number written with a specified number of decimals:

Example

let x = 9.656;
x.toFixed(0);
x.toFixed(2);
x.toFixed(4);
x.toFixed(6);

Try it Yourself » toFixed(2) is perfect for working with money. The toPrecision() Method toPrecision() returns a string, with a number written with a specified length:

Example

let x = 9.656;
x.toPrecision();
x.toPrecision(2);
x.toPrecision(4);
x.toPrecision(6);
The valueOf() Method valueOf() returns a number as a number.

Example

let x = 123;
x.valueOf();
(123).valueOf();
(100 + 23).valueOf();

Formula

In JavaScript, a number can be a primitive value (typeof = number) or an object (typeof = object).

The valueOf()

method is used internally in JavaScript to convert Number objects to primitive values. There is no reason to use it in your code.

All JavaScript data types have a valueOf()

and a toString() method.

Converting Variables to Numbers

There are 3 JavaScript methods that can be used to convert a variable to a number:

Method

Description

Number()

Returns a number converted from its argument. parseFloat() Parses its argument and returns a floating point number parseInt() Parses its argument and returns a whole number

The methods above are not number methods. They are global

JavaScript methods.

The Number() Method

The

Number()

method can be used to convert JavaScript variables to numbers:

Previous

JavaScript String Templates

Next

JavaScript Date Formats