字符串到数字转换:
在Typescript中,我们通过以下方式将字符串转换为数字:
ParseInt() :此函数有2个参数,第一个是要解析的字符串 . 第二个是基数(数学数字系统中的基数,例如10表示十进制,2表示二进制) . 然后返回整数,如果第一个字符无法转换为数字,则返回 NaN .
ParseFloat() :将我们要解析的值作为参数,并返回浮点数 . 如果该值无法转换为数字,则返回 NaN .
+ 运算符:正确使用运算符时,可以将字符串值强制转换为数字 .
示例:
/* 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);
使用哪个?
如果希望将字符串转换为 integer ,请使用 ParseInt() . 但是,数据类型仍然是一个浮点数,因为 all number values are floating point values in TS . 当您需要指定要解析的数字的基数时,也可以使用此方法 .
当需要将字符串解析为 floating point number 时,请使用 ParseFloat() .
您可以在字符串前使用 + 运算符将其强制转换为 floating point number . 这样做的好处是语法非常短 .