TypeScript 将字符串转换为数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14667713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 00:59:10  来源:igfitidea点击:

TypeScript Converting a String to a number

typescript

提问by Paul0515

Anyone a suggestion on how to convert a string to a number in TypeScript?

有人对如何在 TypeScript 中将字符串转换为数字提出建议吗?

var aNumber : number = "1"; // --> Error

// Could this be done?
var defaultValue = 0;
var aNumber : number = "1".toInt32(defaultValue);

// Or ..
var defaultValue = 0;
var aNumber : number = StringToInt("1", defaultValue);

Update: I did some extra puzzling, the best sofar I've come up with: var aNumber : number = ( "1") * 1;

更新:我做了一些额外的令人费解的事情,我想出的最好的: var aNumber : number = ("1") * 1;

checking if a string is numeric is answered here: In Typescript, How to check if a string is Numeric.

此处回答检查字符串是否为数字:在 Typescript 中,如何检查字符串是否为数字

回答by Ryan Cavanaugh

You can use the parseIntor parseFloatfunctions, or simply use the unary +operator:

您可以使用parseIntorparseFloat函数,或者简单地使用一元运算+符:

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

回答by Philip

The Typescript way to do this would be:

执行此操作的 Typescript 方法是:

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

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

在这里回答:https: //stackoverflow.com/a/23440948/2083492

回答by phil294

For our fellow Angular users:

对于我们的 Angular 用户:

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

模板中Number(x)parseInt(x)抛出错误,并且+x没有效果。有效的转换将为x*1x/1

回答by 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 parseIntthough.

不过,我还想再提一件事parseInt

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 canbe omitted. For binary, it's a 2and 16for hexadecimal. Actually, any radix between and including 2 and 36 works.

使用时parseInt始终传递基数参数是有意义的。对于十进制转换,即10. 这是参数的默认值,因此可以省略它。对于二进制,它是一个216十六进制。实际上,介于 2 和 36 之间(包括 2 和 36)的任何基数都有效。

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

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

The parseIntfunction, well, parses strings to convert them to numbers. In some JS implementations, parseIntparses leading zeros as octal:

parseInt函数解析字符串以将它们转换为数字。在一些 JS 实现中,parseInt将前导零解析为八进制:

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

尽管 ECMAScript 3 不鼓励并且 ECMAScript 5 禁止,但许多实现会将以 0 开头的数字字符串解释为八进制。以下可能有八进制结果,也可能有十进制结果。始终指定一个基数以避免这种不可靠的行为。

MDN

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

代码变得更清晰的事实是指定基数参数的一个很好的副作用。

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

由于parseFloat只解析基数为 10 的数值表达式,因此这里不需要基数参数。

More on this:

更多关于这个:

回答by user2040786

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

在阐述 Ryan 所说的内容时,TypeScript 包含了一般的 JavaScript 习语。

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.

JavaScript 类型转换中所有有趣的深入细节。

回答by 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 

回答by Willem van der Veen

String to number conversion:

字符串到数字的转换:

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

在 Typescript 中,我们通过以下方式将字符串转换为数字:

  • 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, NaNwill 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, NaNis returned.
  • +operator: The operator when used appropriately can coerce a string value into a number.
  • ParseInt(): 这个函数有 2 个参数,第一个是要解析的字符串。第二个是基数(数学数字系统中的基数,例如十进制为 10,二进制为 2)。然后它返回整数,如果第一个字符不能转换成数字,NaN则返回。
  • ParseFloat(): 将我们要解析的值作为参数,并返回一个浮点数。如果该值无法转换为数字,NaN则返回。
  • +运算符:适当使用的运算符可以将字符串值强制转换为数字。

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.
  1. 使用ParseInt()当你想要一个字符串转换为整数。但是,数据类型仍然是浮点数,因为所有数值都是 TS 中的浮点值。当您需要指定要解析的数字的基数时,也可以使用此方法。
  2. 使用ParseFloat()时,你需要一个字符串解析为一个浮点数
  3. 您可以+在字符串前使用运算符将其强制转换为浮点数。这样做的好处是语法很短。

回答by Ben Dev

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

最简单的方法是使用 +strVal 或 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

回答by user2569050

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

数字转换器

回答by Kanish Mathew

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

使用 => convertstring('10.00') 调用函数

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

parseFloat(string) => 可以用来转浮点数,toFixed(4) => 转多少位小数

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

parseInt(str) => 可以用来转换成整数

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