Published
Edited
Sep 11, 2019
1 star
Insert cell
md`# Javascript Numbers
Converting a string that contains a number to a Number in JavaScript has many approaches. Heres a notebook with some interesting edgecases, inspired by a tweet you can follow at https://twitter.com/bitandbang/status/1171615896374321152`
Insert cell
md `## Number
It's a good approach to use the Number constructor to do this. Think of Boolean(thing) vs. !!thing. Using a constructor explicitly conveys what you're trying to do.`
Insert cell
Number("1")
Insert cell
new Number("1")
Insert cell
Number("123xyz")
Insert cell
["1", "2", "3"].map(Number)
Insert cell
md `## unary operator`
Insert cell
+"1"
Insert cell
+"1.3"
Insert cell
md `## parseInt`
Insert cell
parseInt("123xyz")
Insert cell
parseInt(010)
Insert cell
["1", "2", "3"].map(parseInt)
Insert cell
md `For more context on parseInt and map see https://wsvincent.com/javascript-parseint-map/`
Insert cell
md `## parseFloat`
Insert cell
["1", "2", "3"].map(parseFloat)
Insert cell
md `## uint32, unsigned 32bit integer`
Insert cell
"1" >>> 0
Insert cell
md `## int32, Signed 32bit integer`
Insert cell
"2.3" >> 0
Insert cell
"2.3"|0
Insert cell
md `## Double bitwise NOT`
Insert cell
~~"2.3"
Insert cell
~~"1"
Insert cell
md `For more context on the double bitwise NOT operator see https://j11y.io/cool-stuff/double-bitwise-not/`
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more