ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
**parseFloat()和+/-用法** ``` // parseFloat() var str = '123'; console.log(parseFloat(str)); // + var str = '123'; console.log(+str); // - var str = '123'; console.log(-str); ``` | 示例 | parseFloat() | + | - | | --- | --- | --- | --- | | ‘123' | 123 | 123 | -123 | | '123.5' | 123.5 | 123.5 | -123.5 | | '456.56.78' | 456.56 | NaN | NaN | | '789.5aa' | 789.5 | NaN | NaN | | '789.56.89aa' | 789.56 | NaN | NaN | | 'abc456.22' | NaN | NaN | NaN | | true | NaN | 1 | 1 | | false | NaN | 0 | 0 | **举例:** ``` var s1 = '123'; var s2 = '123.5'; var s3 = '456.56.78'; var s4 = '789.5aa'; var s5 = '789.56.89aa'; var s6 = 'abc456.22'; var s7 = true; var s8 = false; console.log('------------- parseFloat() ---------') console.log(parseFloat(s1)); //:123 console.log(parseFloat(s2)); //:123.5 console.log(parseFloat(s3)); //:456.56 console.log(parseFloat(s4)); //:789.5 console.log(parseFloat(s5)); //:789.56 console.log(parseFloat(s6)); //:NaN console.log(parseFloat(s7)); //:NaN console.log(parseFloat(s8)); //:NaN console.log('------------- + ---------') console.log(+s1); console.log(+s2); console.log(+s3); console.log(+s4); console.log(+s5); console.log(+s6); console.log(+s7); console.log(+s8); console.log('------------- - ---------') console.log(-s1); console.log(-s2); console.log(-s3); console.log(-s4); console.log(-s5); console.log(-s6); console.log(-s7); console.log(-s8); ``` 效果: ![](https://img.kancloud.cn/36/3b/363bba16e8a251f91b3a51a1c715176a_599x617.png) **注意:** 1.**(变量 - 0)** 转换成数值类型的另外一种方法 2.**(变量 + 0)** 字符串的拼接 ``` var str = '123'; console.log(str - 0); //转换成功输出数值,否则输出:NaN ```