1121

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`? */;
cubuspl42
  • 6,301
  • 4
  • 33
  • 56
Paul0515
  • 17,167
  • 9
  • 28
  • 45
  • 1
    Possible duplicate of [In Typescript, How to check if a string is Numeric](http://stackoverflow.com/questions/23437476/in-typescript-how-to-check-if-a-string-is-numeric) – Jordan.J.D Jan 11 '17 at 16:32
  • 2
    @o_nix It tricks the compiler, it does not change type type: `console.log(typeof "1", typeof Number("1"))` will print `string number`. – k0pernikus Jul 18 '19 at 12:51

16 Answers16

1763

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

Thanatos
  • 37,926
  • 14
  • 76
  • 136
Ryan Cavanaugh
  • 164,706
  • 43
  • 239
  • 219
  • 276
    small hint: parseInt(null) returns NaN but +null returns 0 – Robin J Feb 01 '18 at 14:46
  • 22
    Not as expressive as Philip's higher-rated answer here that does this the TypeScript way. – Patrick Sep 23 '18 at 20:27
  • 13
    There is no TypeScript way because TypeScript is just JavaScript. – thedayturns Jan 14 '19 at 22:19
  • 63
    @thedayturns there is no programming way since programming is just electricity – jiroch Jul 09 '19 at 14:08
  • 3
    @Patrick not sure why you're calling that the "TypeScript" way since it's also just plain Javascript... – Sandy Gifford Apr 22 '20 at 15:14
  • 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: https://medium.com/@nikjohn/cast-to-number-in-javascript-using-the-unary-operator-f4ca67c792ce – cubuspl42 Jun 01 '20 at 21:40
  • + for +. Elegant – Dani Sep 22 '20 at 13:58
  • `+undefined` will also return `NaN` – Не быть рабом на Руси Mar 03 '21 at 09:36
1258

The Typescript way to do this would be:

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

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

Community
  • 1
  • 1
Philip
  • 19,974
  • 2
  • 28
  • 31
121

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.

phil294
  • 8,501
  • 7
  • 55
  • 84
  • that's wonderful! as you said in HTML +x doesn't convert to number at all – sa_ Aug 17 '17 at 18:05
  • 7
    That's because `Number` isn't in the evaluation scope. You can write `class MyComponent { Number = Number; }` to use it. – Aluan Haddad Feb 11 '18 at 22:48
93

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:

Fabian Lauer
  • 5,893
  • 3
  • 20
  • 31
61

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.

user2040786
  • 627
  • 4
  • 2
26

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 
Labib Hussain
  • 462
  • 5
  • 8
19

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.
Willem van der Veen
  • 19,609
  • 11
  • 116
  • 113
12

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
Ben Dev
  • 453
  • 6
  • 9
7

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

sqluser
  • 5,145
  • 7
  • 32
  • 48
Mighty God Loki
  • 125
  • 3
  • 9
4

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
}
Kanish Mathew
  • 595
  • 5
  • 5
4

var myNumber: number = 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

Online Number Conversion Tool

Number Converter

user2569050
  • 185
  • 1
  • 5
3

There are three ways

 let a = + '12'; 
 let b = parseInt('12' , 10); // 10 means decimal number
 let c = Number('12');
Naveed Ullah
  • 101
  • 7
3

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);
}

Ernesto
  • 1,911
  • 1
  • 9
  • 18
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
  }
}
cancerbero
  • 5,662
  • 1
  • 26
  • 18
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("");
Tienanhvn
  • 31
  • 5
  • 7
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);    
   }
James W Simms
  • 761
  • 1
  • 6
  • 9