JavaScript provides a range of methods for handling and manipulating numbers. These methods allow you to format numbers, convert between different number representations, and validate numerical inputs. Understanding these methods is essential for effective numerical computations in web applications.
Number Methods and Properties
Primitive values (like 3.14 or 2014), cannot have properties and methods (because they are not objects).
But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.
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
x.toString(); // returns 123 from variable x
(123).toString(); // returns 123 from literal 123
(100 + 23).toString(); // returns 123 from expression 100 + 23
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
x.toExponential(2); // returns 9.66e+0
x.toExponential(4); // returns 9.6560e+0
x.toExponential(6); // returns 9.656000e+0
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
x.toFixed(0); // returns 10
x.toFixed(2); // returns 9.66
x.toFixed(4); // returns 9.6560
x.toFixed(6); // returns 9.656000
toFixed(2)
is perfect for working with money.
The toPrecision() Method
toPrecision()
returns a string, with a number written with a specified length:
Example
x.toPrecision(); // returns 9.656
x.toPrecision(2); // returns 9.7
x.toPrecision(4); // returns 9.656
x.toPrecision(6); // returns 9.65600
The valueOf() Method
valueOf()
returns a number as a number.
Example
x.valueOf(); // returns 123 from variable x
(123).valueOf(); // returns 123 from literal 123
(100 + 23).valueOf(); // returns 123 from expression 100 + 23
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.
This HTML document demonstrates how each of the number methods can be used in a practical web application. By running this code, you can see how these methods manipulate and interact with numerical values.
Practice Excercise Practice now