Start learning free

LESSON 16 OF 348 · VARIABLES

Type Conversion in TypeScript: String, parseInt and Math.trunc

Lesson Read the full explanation

In JavaScript, every value has a type: number, string, boolean, and so on. Sometimes you need to convert a value from one type to another. This is called type conversion.

Use these functions to convert between types:

String(x)      // converts x to a string
Number(x)      // converts x to a number
parseInt(x)    // converts x to an integer (drops decimals)
parseFloat(x)  // converts x to a float

Here are some examples:

let score = 42;
let scoreStr = String(score);        // "42"  (number → string)

let weight = 70.8;
let weightInt = parseInt(weight);    // 70    (float → integer, decimal dropped)

let count = "100";
let countInt = parseInt(count);      // 100   (string → integer)

Note that parseInt drops the decimal part - it does not round.

parseInt(9.99)  // → 9
parseInt(3.1)   // → 3

Assignment
Follow the Coding Tutorial and convert each variable to a different type!


Hint
Use String() and parseInt().

STEP 1 OF 3
    Ctrl + Enter to check

    TYPESCRIPT · VARIABLES

    Type Conversion in TypeScript, explained

    What type conversion is

    Every value has a type, such as number, string or boolean. Type conversion means producing a new value of a different type from an existing one: the number 25 becomes the string "25", or the string "2024" becomes the number 2024. You need it whenever data arrives in one form and you want to use it in another, for example text typed by a user that you want to do arithmetic on.

    One point matters more than any function: TypeScript's types exist only while the compiler checks your code. They are erased when the code is compiled to JavaScript, so a type annotation never converts anything. Writing const n: number = "5" is reported as a type error, and a cast such as raw as number only tells the compiler to trust you. To really change a value at run time, you call a function.

    The conversion functions

    These are the tools the lesson uses:

    • String(x) returns the text form of any value.
    • Number(x) converts a string (or another value) to a number, and gives NaN if it can't.
    • parseInt(text) reads an integer from the start of a string and stops at the first character that doesn't belong.
    • parseFloat(text) does the same for numbers with a decimal part.
    • Math.trunc(n) removes the fractional part of a number.

    Here they are on small examples, with the output I got from running them:

    const age: number = 25;
    const ageStr: string = String(age);
    console.log(ageStr, typeof ageStr);       // 25 string
    
    const year: string = "2024";
    const yearInt: number = parseInt(year);
    console.log(yearInt, typeof yearInt);     // 2024 number
    
    console.log(parseFloat("3.9abc"));        // 3.9
    console.log(String(true), String(null));  // true null
    

    Converting a number to an integer

    JavaScript's parseInt is a function for strings. Its parameter is typed as a string, so parseInt(9.99) is a type error that the compiler reports ("Argument of type 'number' is not assignable to parameter of type 'string'"). The JavaScript that tsc still writes happens to run and prints 9, because parseInt turns its argument into text first, but the error is a sign that the code does not say what you mean. A number in TypeScript is always a floating-point value, and there is no separate integer type. To "turn it into an integer" you remove the fraction, and Math.trunc does exactly that:

    const price: number = 9.99;
    console.log(Math.trunc(price));   // 9
    console.log(Math.round(price));   // 10
    console.log(Math.trunc(-9.99));   // -9
    console.log(Math.floor(-9.99));   // -10
    

    Note the difference between the functions. Math.trunc drops the decimals, so 9.99 becomes 9, not 10. Math.round goes to the nearest integer. For negative numbers, Math.trunc moves toward zero while Math.floor moves down, which is why they disagree on -9.99. The result is still a number: the value 9 is typed the same as 9.99.

    Gotchas

    • Casts don't convert. If a value of type any holds the string "5", then raw as number still holds a string at run time. Adding 1 gives "51", not 6, because + joins strings. Use Number(raw).
    • parseInt is forgiving, Number is strict. parseInt("42px") gives 42, while Number("42px") gives NaN. An empty string behaves differently again: Number("") is 0 but parseInt("") is NaN.
    • NaN is a number. parseInt("abc") returns NaN, whose type is number, so the compiler can't warn you. Check with Number.isNaN when the input is untrusted.
    • Non-decimal text. parseInt("ff", 16) reads hexadecimal and gives 255. Passing the base explicitly avoids surprises, since parseInt("0x1f") is read as hexadecimal without being asked.

    The exercise, step by step

    The starter code declares three constants:

    const age: number = 25;
    const price: number = 9.99;
    const year: string = "2024";
    

    You add a converted version of each one underneath, with the type that fits the result.

    1. ageStr. The source is a number and the target is a string, so String(age) is the right call. The annotation is string.
    2. priceInt. The source is already a number, so the job is to remove the fraction. Math.trunc(price) gives 9. The annotation stays number, and parseInt would be reported as a type error here.
    3. yearInt. The source is a string of digits, which is what parseInt expects. parseInt(year) gives the number 2024.

    The complete solution:

    const age: number = 25;
    const price: number = 9.99;
    const year: string = "2024";
    
    const ageStr: string = String(age);
    const priceInt: number = Math.trunc(price);
    const yearInt: number = parseInt(year);
    

    Nothing is printed, because the lesson only asks for the three declarations. Add a console.log of each one if you want to see the values: 25, 9 and 2024, with the first one being text.

    Key takeaways

    • Annotations and as casts are erased at compile time and convert nothing. Functions convert.
    • Use String(x) for number to string, and parseInt, parseFloat or Number for string to number.
    • To drop the decimals of a number, use Math.trunc. It truncates; it does not round.
    • A failed conversion gives NaN, not an error.
    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free