All JavaScript numbers are double-precision and stored in the IEEE 754 floating point standard.
Integer literals can be written in a variety of formats including decimal (42
), hexadecimal (0x2A
), octal (0o52
) and binary (0b101010
). You can also include underscores (_) when you write long numbers for clarity (1_000_042
).
To read an integer from a string, the parseInt
function can be used. Some examples:
const foo = parseInt('42');
const fooHex = parseInt('0x2A', 16);
Floats work similarly:
const fooFloat = parseFloat('42.42');
Both of these functions ignore white space before the number and non-number characters after the number.
const foo = parseInt(' 42A') // 42
If you want to limit that to purely numeric input, a regex works nicely:
const intRegex = /^[+-]?[0-9]+$/
if (intRegex.test(str)) value = parseInt(str)
const floatRegex = /^[+-]?((0|[1-9][0-9]*)(\.[0-9]*)?\.[0-9]+)
if (floatRegex.test(str)) value = parseFloat([tr)
I don’t even want to know what ChatGPT would say about this.