How to convert a string to number in TypeScript?

Typescript

Typescript Problem Overview


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`? */;

Typescript Solutions


Solution 1 - Typescript

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

Solution 2 - Typescript

The Typescript way to do this would be:

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

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

Solution 3 - Typescript

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.

Solution 4 - Typescript

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:

Solution 5 - Typescript

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.

Solution 6 - Typescript

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.

Solution 7 - Typescript

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 

Solution 8 - Typescript

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

Solution 9 - Typescript

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

Solution 10 - Typescript

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
}

Solution 11 - Typescript

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

Solution 12 - Typescript

There are three ways

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

Solution 13 - Typescript

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

Solution 14 - Typescript

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

Solution 15 - Typescript

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("");

Solution 16 - Typescript

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

Solution 17 - Typescript

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

var numberString: string = "1234";
const numberValue = numberString as number;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPaul0515View Question on Stackoverflow
Solution 1 - TypescriptRyan CavanaughView Answer on Stackoverflow
Solution 2 - TypescriptPhilipView Answer on Stackoverflow
Solution 3 - Typescriptphil294View Answer on Stackoverflow
Solution 4 - TypescriptFabian LauerView Answer on Stackoverflow
Solution 5 - Typescriptuser2040786View Answer on Stackoverflow
Solution 6 - TypescriptWillem van der VeenView Answer on Stackoverflow
Solution 7 - TypescriptLabib HussainView Answer on Stackoverflow
Solution 8 - TypescriptBen DevView Answer on Stackoverflow
Solution 9 - TypescriptMighty God LokiView Answer on Stackoverflow
Solution 10 - TypescriptKanish MathewView Answer on Stackoverflow
Solution 11 - Typescriptuser2569050View Answer on Stackoverflow
Solution 12 - TypescriptNaveed UllahView Answer on Stackoverflow
Solution 13 - TypescriptErnestoView Answer on Stackoverflow
Solution 14 - TypescriptcancerberoView Answer on Stackoverflow
Solution 15 - TypescriptTienanhvnView Answer on Stackoverflow
Solution 16 - TypescriptJames W SimmsView Answer on Stackoverflow
Solution 17 - TypescriptXDavidTView Answer on Stackoverflow