Number Parsing in TypeScript
Parsing numbers from strings is a basic but common task in many programs; here’s how to do it in TypeScript.
// TypeScript doesn't have a built-in package for number parsing
// like Go's strconv, but we can use JavaScript's built-in functions
function main() {
// With parseFloat, we don't need to specify precision
const f = parseFloat("1.234");
console.log(f);
// parseInt takes a radix parameter, 10 for decimal
const i = parseInt("123", 10);
console.log(i);
// parseInt will recognize hex-formatted numbers
const d = parseInt("0x1c8", 16);
console.log(d);
// There's no direct equivalent to ParseUint, but we can use parseInt
const u = parseInt("789", 10);
console.log(u);
// There's no direct equivalent to Atoi, but parseInt works similarly
const k = parseInt("135", 10);
console.log(k);
// Parsing functions return NaN on bad input
const badParse = parseInt("wat", 10);
console.log(isNaN(badParse) ? "Invalid syntax" : badParse);
}
main();
To run the program, save it as number-parsing.ts
and use ts-node
(assuming you have it installed):
$ ts-node number-parsing.ts
1.234
123
456
789
135
Invalid syntax
In TypeScript, we use JavaScript’s built-in parseFloat
and parseInt
functions for number parsing. Unlike Go’s strconv
package, these functions don’t require importing any modules.
parseFloat
is used for parsing floating-point numbers. It doesn’t require specifying precision as it uses JavaScript’s default number precision.
parseInt
is used for parsing integers. It takes two arguments: the string to parse and the radix (base of the number system). For decimal numbers, we use radix 10. For hexadecimal numbers, we use radix 16.
TypeScript doesn’t have a direct equivalent to Go’s ParseUint
, but parseInt
can be used for parsing unsigned integers as well.
There’s no direct equivalent to Go’s Atoi
function, but parseInt
with a radix of 10 serves the same purpose for parsing base-10 integers.
When parsing fails, these functions return NaN
(Not-a-Number) instead of an error. We can use the isNaN
function to check if parsing was successful.
Next, we’ll look at another common parsing task: URLs.