Top 5 ways to Convert Number to/from String in typescript?

Have you ever encountered a situation where you needed to convert a number to a string or vice versa in TypeScript?

This scenario frequently arises during the development of Angular/TypeScript-based projects, prompting the creation of this blog post.

In the TypeScript programming language, the fundamental data types Number and String are basic built-in primitive data types that are well-known to developers.

The Number type represents numeric values, while the String type represents a sequence of characters enclosed in either double or single quotes.

These data types hold distinct values, and because TypeScript doesn’t automatically convert between them, developers often find themselves writing code to perform manual conversions.

Converting between number and string is a common task for TypeScript developers. For instance, to convert a string to a number, the string must contain only numeric characters.

How to Convert Numbers to Strings in TypeScript: Examples

There are multiple methods to convert a number to a string in JavaScript or TypeScript:

  • Append with an empty string.

  • Using the toString() method.

  • Using the string constructor.

    You can check another post on Fix for Object is possibly null

  • Using Append Number with an Empty String

    This method is straightforward and easy to use for parsing a number into a string. By adding an empty string to a number, it converts it into a string representation.

    In TypeScript, the + operator is used to concatenate strings. The typeof method checks the value type and returns the primitive type as a string.

    Here are examples of converting valid and invalid values to a string:

    The below example number is a valid numeric value ie 12,

    var a: number = 12;
    var str: string = a + "";
    console.log(typeof a); // Output: number
    console.log(typeof str); // Output: string
    console.log(str); // Output: "12"
    

    The below example shows the numeric variable with null.

    var a: number = null;
    var str: string = a + "";
    console.log(typeof str); // Output: string
    console.log(str); // Output: "null"
    

    The below example shows the numeric variable with undefined.

    var a: number = undefined;
    var str: string = a + "";
    console.log(typeof str); // Output: string
    console.log(str); // Output: "undefined"
    
  • Using the toString() Method

    The toString() method is an in-built method that every data type has. It returns a string version of an object.

    calling the toString() method on any data type returns a string object.

    var a: number = 17;
    var str: string = a.toString();
    console.log(typeof str); // Output: string
    console.log(a); // Output: "17"
    

    If used with null or undefined, the compiler throws the Cannot read property 'toString' of null error.

  • Using the String Constructor

    The string constructor accepts any value and returns a string. This approach is useful when creating a string and is the easiest way to convert numbers to string types.

    Here is an example

    var a: number = 12;
    var stringValue = String(a);
    console.log(typeof(stringValue)); // Output: string
    

How to Convert String to Number in TypeScript: An Example

This section addresses several common problems:

  • How to convert a string to an integer?
  • How to parse a string into floating-point numbers with decimal precision?

Firstly, the string must contain numeric values enclosed in single or double quotes. If the input is a valid string numeric value, such as 123, the output will always return 123 of the type number. However, if the string is not a numeric value, all these conversion methods return the NaN value.

There are multiple ways to convert a string to a number.

  • parseInt method

  • parseFloat method

  • Number() constructor

  • Plus operator

  • Using parseInt() Native Method

    It is used to parse a string to a number in decimal places.

    parseInt is an inbuilt method that takes input numbers in the form of a string and returns numbers.

    Syntax:

    parseInt(string, radix);
    

    Here, the string is a numeric string enclosed in single or double quotes, and radix is an optional parameter. Possible values for radix are:

    • 16 - Hexa number,
    • 8 - Octa number
    • 2 - Binary number
    • 10 - Decimal number ie default

    The possible outputs are:

    • Valid number: if the string is valid numeric values enclosed in single or double quotes
    • NaN: if the input string is either not a valid number or null or undefined.
    console.log(parseInt("32", 10)); // outputs 32
    console.log(parseInt("45")); // outputs 45
    console.log(parseInt("45abc")); // outputs 45
    console.log(parseInt("null")); // outputs NaN
    console.log(parseInt("45")); // outputs 45
    
  • Using parseFloat() Method

    parseFloat is an inbuilt method that accepts a number in string format and converts it to a number in floating number format.

    The possible outputs are:

    • Valid floating number: if the string is valid numeric values enclosed in single or double quotes
    • NaN: if the input string is not a valid numeric value or null or undefined.

    Syntax:

    parseFloat(string, radix);
    

    Here is an example

    console.log(parseFloat("32.32")); // outputs 32.32 as output
    

    This method is useful for converting to floating numbers that contain decimal places.

  • Using Number() Method

    The Number() constructor takes a string as a parameter and returns a number as the output.

    console.log(Number("12")); // outputs 12 as output
    console.log(Number("null")); // outputs NaN as output
    console.log(Number("undefined")); // outputs NaN as output
    
  • Using Plus Unary Operator This is a unary operator which accepts only one operand. It accepts strings, boolean values, and all types of numbers and converts them to numbers.

    Syntax:

    +string / boolean / number;
    

    Input is

    • string
    • boolean
    • all number types - Hexa, octal, floating numbers

    The possible outputs are:

    • Valid number: if the string is valid numeric values enclosed in single or double quotes
    • NaN: if the input string is not a valid numeric value or null or undefined.
    console.log(+"44"); // outputs 44
    console.log(+"44.23"); // outputs 44.23
    console.log(+true); // outputs 1
    console.log(+false); // outputs 0
    console.log(+undefined); // outputs 0
    console.log(+null); // outputs 0
    

Conclusion

It is important to learn the possible ways of TypeScript conversion with primitive types. Most of the above examples will work in JavaScript because TypeScript is a superset of JavaScript.

I hope you have learned many ways to convert strings to/from numbers in TypeScript. Additionally, ensure that you are sending valid strings with numbers for conversion; this is a very easy way to parse numbers.

Reference: