[typescript] How to convert a string to number in TypeScript?

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

This question is related to typescript

The answer is


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 

_x000D_
_x000D_
var myNumber: number = 1200;_x000D_
//convert to hexadecimal value_x000D_
console.log(myNumber.toString(16)); //will return  4b0_x000D_
//Other way of converting to hexadecimal_x000D_
console.log(Math.abs(myNumber).toString(16)); //will return  4b0_x000D_
//convert to decimal value_x000D_
console.log(parseFloat(myNumber.toString()).toFixed(2)); //will return  1200.00
_x000D_
_x000D_
_x000D_

Online Number Conversion Tool

Number Converter


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.

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


The Typescript way to do this would be:

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

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


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:


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

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.


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

There are three ways

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

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
}

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


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:

_x000D_
_x000D_
/*    parseInt   */_x000D_
_x000D_
// note that a whole number is returned, so it will round the number_x000D_
console.log(parseInt('51.023124'));_x000D_
_x000D_
// parseInt will 'cut off' any part of the string which is not a number_x000D_
console.log(parseInt('5adfe1234'));_x000D_
_x000D_
// When the string starts with non number NaN is returned_x000D_
console.log(parseInt('z123'));_x000D_
_x000D_
console.log('--------');_x000D_
_x000D_
/*    parseFloat   */_x000D_
_x000D_
// parses the string into a number and keeping the precision of the number_x000D_
console.log(typeof parseFloat('1.12321423'));_x000D_
_x000D_
// parseFloat will 'cut off' any part of the string which is not a number_x000D_
console.log(parseFloat('5.5abc'));_x000D_
_x000D_
console.log('--------');_x000D_
_x000D_
/*   + operator   */_x000D_
_x000D_
let myString = '12345'_x000D_
_x000D_
console.log(typeof +myString);_x000D_
_x000D_
let myOtherString = '10ab'_x000D_
_x000D_
// + operator will not cut off any 'non number' string part and will return NaN_x000D_
console.log(+myOtherString);
_x000D_
_x000D_
_x000D_

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.

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.


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


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