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.
To run the program, save it as number-parsing.ts
and use ts-node
(assuming you have it installed):
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.