# Number object
# Frequently used methods
method | description |
---|---|
toFixed(<digits>) (opens new window) | formats a number as a string using fixed-point notation (with <digits> the number of digits after the decimal point) |
Number.isInteger(<value>) (opens new window) * | returns true if the passed <value> is an integer, and false if not |
parseInt(<str>) (opens new window) ** | converts the numeric string <str> to an integer |
parseFloat(<str>) (opens new window) ** | converts the numeric string <str> to a floating point number |
* This method is a so-called static method and should be preceded by Number.
** These methods are also static methods (and can be called as e.g. Number.parseInt(<str>)
), but they also exist as global functions (and can be called as e.g. parseInt(<str>)
)
TIP
- Instead of using
parseInt()
andparseFloat()
, you can also place a+
sign just before the numeric stringconst a = +'5.5'
is the same asconst a = parseFloat('5.5')
const b = +'7'
is the same asconst b = parseInt('7')
# Parse numeric input fields
- Numeric input fields ALWAYS return a numeric STRING and not a number
- One of the most common errors with forms is adding two numeric strings (stemming from numeric input fields)
- Open es6/numbers/parse.html and es6/numbers/parse.js
REMARK
The problem/error situated above only occurs when adding numeric strings. If you multiply, subtract, ... number strings, JavaScript automatically takes care of the "parsing" itself:
const nr1 = '5';
const nr2 = '7';
const product = nr1 * nr2;
console.log('nr1 * nr2 =', product); //nr1 * nr2 = 35
console.log(typeof product); //number
1
2
3
4
5
2
3
4
5
# Exercises
- Open exercises/index.html and make the exercises under the tab ES6 > Number object