📝 Edit page
➕ Add page
Cast
Convert between data types
Resources
Number to string
Integer or float
const myNumber = 123
myNumber.toString()
// "123"
Optionally supply 10
as the base.
Note that a method directly on number (without a variable declared first) will give an error.
123.toString()
// Uncaught SyntaxError: Invalid or unexpected token
String to number
Remember that JavaScript as no Int
and Float
types, just Number
.
To integer
parseInt("123")
// 123
parseInt("123.45")
// 123
No effect if already an integer.
parseInt(123)
// 123
Recommended - pass the radix
argument as the base, to avoid linting errors. The base can be inferred, but in some cases will be incorrect so it is better to always set it. See Other number systems section below for other uses of this argument.
parseInt("123", 10)
// 123
parseInt("123.45", 10)
// 123
To float
parseFloat("123.45")
// 123.45
parseFloat("123")
// 123
No change on float input.
parseFloat(123.45)
// 123.45
Other number systems
The base or radix
defaults to 10
but you can specify others.
Parse base 2
parseInt("10", 2)
// 2
Parse hexidecimal
> parseInt("f", 16)
15
> parseInt("0xf")
15
Number base 2 sting
const myNumber = 10
myNumber.toString(2)
// '1010'
Number to base 16 string
const myNumber = 10
myNumber.toString(16)
// 'a'