TypeScript: Convert a String Variable to a Number Variable

Sometimes the basics can stump you. And I was stumped this morning when I needed to convert a TypeScript variable of type “string” to a variable of type “number”, including a non-numeric check.

IsNaN() and parseInt() in JavasScript didn’t work because in TypeScript the input parameters are numbers, so immediately that’s a compile time exception.

After a quick search and trusty StackOverflow answer, I came up with the following function:

/**
 * Return the numeric value of a variable if the value is a number, otherwise return zero (0).
 */
function convertToNumber(value: any) : number 
{
  let convertedToNumber: number = 0;

  if (isNaN(Number(value)) === false) {
    convertedToNumber = Number(value);
  }

  return convertedToNumber;
}

 

Running Example

NOTE: You can pop the editor open in a new window by selecting “Edit On StackBlitz” in the bottom-left of the inserted window.
Select the folded-page icon at the top of the left column (below the StackBlizt blue/white icon) to see the list of files.

If you’re using Internet Explorer or there’s just a black window below, here’s the link to the code (and I suggest using a “modern” browser – Chrome and Edge both work): https://stackblitz.com/edit/typescript-x2hpkw.