ChatGPT解决这个技术问题 Extra ChatGPT

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`? */;
@o_nix It tricks the compiler, it does not change type type: console.log(typeof <number><any>"1", typeof Number("1")) will print string number.

T
Thanatos

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).

https://i.stack.imgur.com/QNMfI.png


small hint: parseInt(null) returns NaN but +null returns 0
Not as expressive as Philip's higher-rated answer here that does this the TypeScript way.
There is no TypeScript way because TypeScript is just JavaScript.
@thedayturns there is no programming way since programming is just electricity
@Patrick not sure why you're calling that the "TypeScript" way since it's also just plain Javascript...
C
Community

The Typescript way to do this would be:

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

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


Note: you can check for NaN using the isNaN function.
Note that this wont't work:let value : number = valueAsString;
I think new Number("1234").valueOf() is really what we are all looking for-
@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.
small hint: don't use new Number() as it will produce type Number instead of number. Use Number()
p
phil294

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.


that's wonderful! as you said in HTML +x doesn't convert to number at all
That's because Number isn't in the evaluation scope. You can write class MyComponent { Number = Number; } to use it.
F
Fabian Lauer

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:

Why do we need to use radix? (SO Question)

SO Answer to "What is the difference between parseInt() and Number()?"


and one more: ~~'123' (using internal ToInt32)
u
user2040786

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.


M
Manfred

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?

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. Use parseFloat() when you need to parse a string into a floating point number. 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.


Great explanation. Helped me a lot, sir!
L
Labib Hussain

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 

2
2pichar

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


s
sqluser

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


K
Kanish Mathew

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
}

s
sneha rani

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


N
Naveed Ullah

There are three ways

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

E
Ernesto

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


c
cancerbero

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

T
Tienanhvn

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

J
James W Simms

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

It allows an optional sign to appear in front or behind the numeric value. It performs a check to verify there is only one sign at the head or tail of the string. 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 = +(val); if( (r != null) && (!isNaN(r)) ) { result = r*sign; } return(result); }


X
XDavidT

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

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

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.