1646

Given a string representation of a number, how can I convert it to number type in TypeScript?

var numberString: string = "1234";
var numberValue: number = /* what should I do with `numberString`? */;
2

21 Answers 21

2428

Exactly like in JavaScript, you can use the parseInt or parseFloat functions, or simply use the unary + operator:

var x = "32";
var y: number = +x;

All of the mentioned techniques will have correct typing and will correctly parse simple decimal integer strings like "123", but will behave differently for various other, possibly expected, cases (like "123.45") and corner cases (like null).

Conversion table Table taken from this answer

4
  • 351
    small hint: parseInt(null) returns NaN but +null returns 0
    – Robin J
    Commented Feb 1, 2018 at 14:46
  • 2
    While I wouldn't say that TypeScript is just JavaScript, in this case the answer is indeed "do that exactly the same way as in JavaScript". All techniques from all the answers on this page behave correctly type-wise. I cannot see how any of them is more or less "TypeScript way". The solution should be chosen after evaluating how each technique behaves on corner cases. See: medium.com/@nikjohn/…
    – cubuspl42
    Commented Jun 1, 2020 at 21:40
  • +undefined will also return NaN
    – doox911
    Commented Mar 3, 2021 at 9:36
  • In this case, one difference between TypeScript and JavaScript: parseInt(variable, 10) triggers an error in Typescript if the variable if of type string | number and works just fine in JavaScript. Commented Aug 30, 2022 at 12:49
1627

The TypeScript way to do this would be:

Number('1234') // 1234
Number('9BX9') // NaN

as answered here: https://stackoverflow.com/a/23440948/2083492

8
  • 11
    Note: you can check for NaN using the isNaN function. Commented Mar 13, 2017 at 10:22
  • 4
    Note that this wont't work:let value : number = valueAsString;
    – yonexbat
    Commented Mar 19, 2017 at 18:04
  • 3
    I think new Number("1234").valueOf() is really what we are all looking for-
    – chrismarx
    Commented Oct 11, 2017 at 21:55
  • 54
    @Devid - you could simplify to let a = Number('x') || 0; - Number('x') would return NaN, which is "falsey". Therefore, a would be assigned 0. Much cleaner and arguably (slightly) quicker than using the ternary statement and parsing twice. Commented Oct 30, 2017 at 12:00
  • 9
    small hint: don't use new Number() as it will produce type Number instead of number. Use Number() Commented May 21, 2020 at 12:17
149

For our fellow Angular users:

Within a template, Number(x) and parseInt(x) throws an error, and +x has no effect. Valid casting will be x*1 or x/1.

3
  • that's wonderful! as you said in HTML +x doesn't convert to number at all
    – sa_
    Commented Aug 17, 2017 at 18:05
  • 15
    That's because Number isn't in the evaluation scope. You can write class MyComponent { Number = Number; } to use it. Commented Feb 11, 2018 at 22:48
  • ""*1 returns 0 unfortunately
    – vbilenko
    Commented Jun 23, 2023 at 10:17
147

As shown by other answers here, there are multiple ways to do the conversion:

Number('123');
+'123';
parseInt('123');
parseFloat('123.45')

I'd like to mention one more thing on parseInt though.

When using parseInt, it makes sense to always pass the radix parameter. For decimal conversion, that is 10. This is the default value for the parameter, which is why it can be omitted. For binary, it's a 2 and 16 for hexadecimal. Actually, any radix between and including 2 and 36 works.

parseInt('123')         // 123 (don't do this)
parseInt('123', 10)     // 123 (much better)

parseInt('1101', 2)     // 13
parseInt('0xfae3', 16)  // 64227

In some JS implementations, parseInt parses leading zeros as octal:

Although discouraged by ECMAScript 3 and forbidden by ECMAScript 5, many implementations interpret a numeric string beginning with a leading 0 as octal. The following may have an octal result, or it may have a decimal result. Always specify a radix to avoid this unreliable behavior.

MDN

The fact that code gets clearer is a nice side effect of specifying the radix parameter.

Since parseFloat only parses numeric expressions in radix 10, there's no need for a radix parameter here.

More on this:

1
  • 1
    and one more: ~~'123' (using internal ToInt32)
    – aMarCruz
    Commented Jun 25, 2019 at 21:14
70

Expounding on what Ryan said, TypeScript embraces the JavaScript idioms in general.

var n = +"1"; // the unary + converts to number
var b = !!"2"; // the !! converts truthy to true, and falsy to false
var s = ""+3; // the ""+ converts to string via toString()

All the interesting in-depth details at JavaScript Type Conversion.

49

String to number conversion:

In Typescript we convert a string to a number in the following ways:

  • parseInt(): This function takes 2 arguments, the first is a string to parse. The second is the radix (the base in mathematical numeral systems, e.g. 10 for decimal and 2 for binary). It then returns the integer number, if the first character cannot be converted into a number, NaN will be returned.
  • parseFloat(): Takes as an argument the value which we want to parse, and returns a floating point number. If the value cannot be converted to a number, NaN is returned.
  • + operator: The operator when used appropriately can coerce a string value into a number.

Examples:

/*    parseInt   */

// note that a whole number is returned, so it will round the number
console.log(parseInt('51.023124'));

// parseInt will 'cut off' any part of the string which is not a number
console.log(parseInt('5adfe1234'));

// When the string starts with non number NaN is returned
console.log(parseInt('z123'));

console.log('--------');

/*    parseFloat   */

// parses the string into a number and keeping the precision of the number
console.log(typeof parseFloat('1.12321423'));

// parseFloat will 'cut off' any part of the string which is not a number
console.log(parseFloat('5.5abc'));

console.log('--------');

/*   + operator   */

let myString = '12345'

console.log(typeof +myString);

let myOtherString = '10ab'

// + operator will not cut off any 'non number' string part and will return NaN
console.log(+myOtherString);

Which to use?

  1. Use parseInt() when you want a string converted to an integer. However, the data type is still a float, since all number values are floating point values in TS. Also use this method when you need to specifiy the radix of the number you want to parse.
  2. Use parseFloat() when you need to parse a string into a floating point number.
  3. You can use the + operator before a string to coerce it into a floating point number. The advantage of this is that the syntax is very short.
0
43

Easiest way is to use +strVal or Number(strVal)

Examples:

let strVal1 = "123.5"
let strVal2 = "One"
let val1a = +strVal1
let val1b = Number(strVal1)
let val1c = parseFloat(strVal1)
let val1d = parseInt(strVal1)
let val1e = +strVal1 - parseInt(strVal1)
let val2a = +strVal2

console.log("val1a->", val1a) // 123.5
console.log("val1b->", val1b) // 123.5
console.log("val1c->", val1c) // 123.5
console.log("val1d->", val1d) // 123
console.log("val1e->", val1e) // 0.5
console.log("val2a->", val2a) // NaN

31

You can follow either of the following ways.

var str = '54';

var num = +str; //easy way by using + operator
var num = parseInt(str); //by using the parseInt operation 
8

There are inbuilt functions like parseInt(), parseFloat() and Number() in Typescript, you can use those.

6

const myNumber = 1200;
//convert to hexadecimal value
console.log(myNumber.toString(16)); //will return  4b0
//Other way of converting to hexadecimal
console.log(Math.abs(myNumber).toString(16)); //will return  4b0
//convert to decimal value
console.log(parseFloat(myNumber.toString()).toFixed(2)); //will return  1200.00

For reference on converting other formats to decimal

5

Call the function with => convertstring('10.00')

parseFloat(string) => It can be used to convert to float, toFixed(4) => to how much decimals

parseInt(str) => It can be used to convert to integer

convertstring(string){
    let number_parsed: any = parseFloat(string).toFixed(4)
    return number_parsed
}
4

There are three ways

 let a = + '12'; 
 let b = parseInt('12' , 10); // 10 means decimal number
 let c = Number('12');
4

typescript needs to know that our var a is going to ether be Number || String

export type StringOrNumber = number | string;

export function toString (v: StringOrNumber) {
 return `${v}`;
}


export function toNumber (v: StringOrNumber) {
 return Number(v);
}

export function toggle (v: StringOrNumber) {
 return typeof v === "number" ? `${v}` : Number(v);
}

2
let a = '10'
typeof a 

it will return string

Solution 1:

add + before a

this will convert a string-number into number.

let n = +a 
typeof n

will return number

Solution 2:

use Number method, it will convert string into a number

let a = "10";
Number(a)

Solution 3:

parseInt(a);
2
There are three method use for convert string to number. 

const rollNumber = "12345";

console.log(typeof +rollNumber);

console.log(typeof Number(rollNumber));

console.log(typeof parseInt(rollNumber));
  • In all cases, the result is a numeric data type, which is confirmed by the output "number" for each console.log() statement. However, there are some differences in how each method handles the conversion:

  • Unary Plus Operator (+): This operator converts the string to a
    number. It's a concise way to convert strings to numbers, but it only works for converting to numbers, not other numeric types like
    integers.

  • Number() Constructor: The Number() constructor converts its argument to a number. It's more explicit than the unary plus operator and can handle different types of input, not just strings.

  • parseInt(): This function parses a string argument and returns an
    integer. It's commonly used for parsing strings into integer values. If the string contains non-numeric characters after the numeric part, parseInt() will stop parsing and return the numeric part. This
    function is useful when you specifically need an integer result.

1

if you are talking about just types, as other people said, parseInt() etc will return the correct type. Also, if for any reason the value could be both a number or a string and you don't want to call parseInt(), typeof expressions will also cast to the correct type:

function f(value:number|string){
  if(typeof value==='number'){
   // value : number
  }else {
   // value : string
  }
}
1
const add =(test)=>{
// numbers becomes array now :) after split method applied
let numbers = test.split("+");
let sum = 0;
for(let i =0;i < numbers.length;i++){
 sum = sum + Number(numbers[i])
 }
 return sum
  }
0

There are a lot of you are having a problem to convert data types are difficult to solve in the ionic programming situations, because this very language is new, here I will detail instructions for the user to know how to convert data ionic types to string data type integer.

In programming languages such as java, php, c, c++, ... all can move data easily, then in ionic can also create for us data conversion is also an easy way not least in other programming languages.

this.mPosition = parseInt("");
0

Here is a modified version of the StrToNumber function. As before,

  1. It allows an optional sign to appear in front or behind the numeric value.
  2. It performs a check to verify there is only one sign at the head or tail of the string.
  3. If an error occurs, a "passed" default value is returned.

This response is a possible solution that is better suited to the initial question than my previous post.

   static StrToNumber(val: string, defaultVal:number = 0): number
   {        
      let result:number = defaultVal;      
      if(val == null) 
         return result;            
      if(val.length == 0) 
         return result;      
      val = val.trim();
      if(val.length == 0) 
         return(result);
      let sign:number = 1;     
      //
      // . obtain sign from string, and place result in "sign" local variable. The Sign naturally defaults to positive
      //     1 for positive, -1 for negative.
      // . remove sign character from val. 
      //      Note, before the function returns, the result is multiplied by the sign local variable to reflect the sign.
      // . error check for multiple sign characters
      // . error check to make sure sign character is at the head or tail of the string
      //              
      {  
         let positiveSignIndex = val.indexOf('+');
         let negativeSignIndex = val.indexOf('-');
         let nTailIndex = val.length-1;
         //
         // make sure both negative and positive signs are not in the string
         //
         if( (positiveSignIndex != -1) && (negativeSignIndex != -1) ) 
             return result;
         //
         // handle postive sign
         //
         if (positiveSignIndex != -1)
         {
            //
            // make sure there is only one sign character
            //
            if( (positiveSignIndex != val.lastIndexOf('+')) )
             return result;     
             //
             // make sure the sign is at the head or tail
             //
             if( (positiveSignIndex > 0) && (positiveSignIndex < nTailIndex )  )
                 return result;
             //
             // remove sign from string
             //
             val = val.replace("+","").trim();                 
         }    
         //
         // handle negative sign
         //
         if (negativeSignIndex != -1)
         {
            //
            // make sure there is only one sign character
            //
            if( (negativeSignIndex != val.lastIndexOf('-')) )
             return result;     
             //
             // make sure the sign is at the head or tail
             //
             if( (negativeSignIndex > 0) && (negativeSignIndex < nTailIndex )  )
                 return result;
             //
             // remove sign from string
             //
             val = val.replace("-","").trim();  
             sign = -1;                 
         }               
         //
         // make sure text length is greater than 0
         //       
         if(val.length == 0) 
            return result;                             
      }   
      //
      // convert string to a number
      //
      var r = +(<any>val);
      if( (r != null) && (!isNaN(r)) )
      {          
         result = r*sign;         
      }
      return(result);    
   }

0

This would save your few hours,

I was trying to add number like this :

qty += data.acceptedQty;

But it ended up like 1 + 1 = 11; I have fixed it with unary plus operator like this:

qty += +data.acceptedQty;
-8

In the latest version you can use as, here is example:

var numberString: string = "1234";
const numberValue = numberString as number;
1
  • 8
    this does not convert the value, this tell the computer -> shut up, I know what going on, it's a number, trust me. but this do absolutely no real conversion. It may work in some case because there is a lot of place where you can put a string instead of a number and the string will implicitly be converted to number. but it will not always work. Commented Oct 21, 2021 at 19:58

Not the answer you're looking for? Browse other questions tagged or ask your own question.