字符串强制转化数字java_TypeScript将字符串转换为数字

字符串到数字转换:

在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 . 这样做的好处是语法非常短 .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值