Number methods help you to work with numbers.
JavaScript global functions can be used on all JavaScript data types.
These are the most relevant methods, when working with numbers:
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 an integer |
JavaScript number methods are methods that can be used on numbers:
Method | Description |
---|---|
toString() | Returns a number as a string |
toExponential() | Returns a string, with a number rounded and written using exponential notation. |
toFixed() | Returns a string, with a number rounded and written with a specified number of decimals. |
toPrecision() | Returns a string, with a number written with a specified length |
valueOf() | Returns a number as a number |
All number methods return a new variable. They do not change the original variable. |
toString() returns a number as a string.
All number methods can be used on any type of numbers (literals, variables, or expressions):
toExponential() returns a string, with a number rounded and written using exponential notation.
A parameter defines the number of character behind the decimal point:
The parameter is optional. If you don't specify it, JavaScript will not round the number.
toFixed() returns a string, with the number written with a specified number of decimals:
toFixed(2) is perfect for working with money. |
toPrecision() returns a string, with a number written with a specified length:
There are 3 JavaScript functions that can be used to convert variables to numbers:
These methods are not number methods, but global JavaScript methods.
Number(), can be used to convert JavaScript variables to numbers:
parseInt() parses a string and returns a whole number. Spaces are allowed. Only the first number is returned:
If the number cannot be converted, NaN (Not a Number) is returned.
parseFloat() parses a string and returns a number. Spaces are allowed. Only the first number is returned:
If the number cannot be converted, NaN (Not a Number) is returned.
valueOf() returns a number as a number.
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.
In JavaScript, all data types have a valueOf() and a toString() method. |
For a complete reference, go to our Complete JavaScript Number Reference.
The reference contains descriptions and examples of all Number properties and methods.