JavaScript numbers
Number
type
Number
typeJavaScript's Number
type encompasses all kinds of numbers and special cases of numbers:
simple integers (e.g. -2, -1, 0, 1, 2)
floating point decimals (e.g. 0.36, -25.19111)
aka "floats"
infinity (i.e.
Infinity
, e.g. dividing aNumber
by0
)non-number (i.e.
NaN
, e.g. dividing aString
by aNumber
)
Other programming languages might have separate types for each kind of number
JavaScript also supports other number bases, i.e.:
binary (base 2, i.e. only 0 and 1)
octal (base 8, i.e. numbers 0 to 7)
hexadecimal (base 16, i.e. numbers 0 to 9 and a to f)
handy for color hex codes
Adding Number
s to String
s
Number
s to String
sIn JavaScript, if we try to add a Number
to a String
, JavaScript will convert the Number
part of the equation into a String
like such:
Other operations with mixed Number
s and String
s
Number
s and String
sHowever, if we try to perform subtraction, multiplication or division operations with a Number
and a String
, JavaScript will try to convert the String
into a Number
!
Operations with mixed Number
s and Boolean
s
Number
s and Boolean
sNow, how about the crazy idea of performing arithmetic with a Number
and a Boolean
(a true
and false
value)? Well, true
becomes 1
and false
becomes 0
!
Methods for Number
s and related
Number
s and relatedisNaN(input)
Takes in any input as a parameter and returns either true
or false
if a number exists:
Oddly enough, NaN
is a Number
in JavaScript! Try it with typeof NaN
in the console!
Another fun thing to try : NaN === NaN
will be false
!
Another edge case includes:
This happens since isNaN()
tries to convert any passed-in value (argument) into a Number
first. in the case of an empty string, JavaScript will convert that into a 0
. Thus, the empty string is actually considered a Number
!
In ES6, Number
has a separate isNaN()
built-in method, Number.isNaN()
, to address this issue:
Thus, the Number.isNaN()
differes in that it does not coerce the argument into a Number at all!
parseFloat(input)
Takes in any input and tries to find a floating-point decimal number at its beginning:
If the first parts of the String
are non-numeric, it will usually return NaN,
but JavaScript will still try to ignore whitespace and the unary operators ( +
and -
signs)!
parseInt(input)
Similar to `parseFloat`, parseInt stops looking after the first non-digit. It also returns only the integer portion of a floating-point decimal number, with parsing rules similar to the parseFloat
:
Number.toFixed(places)
This converts numbers with a lot of decimal places, such as 3.1415926535 (pi) into a fixed number of decimal places, with rounding included:
Note that the toFixed()
method returns a String
and not a Number
as the primary use case for this result is to display the value rather than perform further calculations
Last updated