字符串转化成整数

看起来容易,但是有好多需要考虑到边界条件。

比如

1.如果含有正负号或者非数字字符怎么办?

2.最大正整数和最小负整数以及溢出

3.输入的字符不能转换成整数的时候,应该如何处理错误

所以其实还是比较复杂。不要看到题目就傻呵呵的写了。= =

JS 中有封装好的parseInt,但是传入的参数要注意:parseInt(string, radix)

1. 当radix<2 / radix > 36时,返回NaN

2.当string中的单个数字大于radix时,返回NaN

3.当radix===0 / 未设置时,根据string来判断

 当string以‘0x’开头时,按照16进制解析

 当string以‘0’开头时,按照八进制解析

 当strign以‘1~9’开头时,按照十进制解析

拓展:(曾经跪在蚂蚁面试中的题)实现一个函数,把输入的数字保留两位小数,不进位,如果不足两位,以0补位。

function twoDecimal(num) {
            var res = '';
            num = parseFloat(num);
            if (typeof num !== 'number' || isNaN(num) || !isFinite(num))
                return 'none valid number';
            else {
                var snum = num.toString();
                var tail = '', e = snum.indexOf('e');
                if (e != -1) {
                    tail += snum.slice(e);
                    snum = snum.slice(0, e);
                }
                var n = snum.split('.');
                if (n.length === 1) {
                    res += n + '.00';
                } else {
                    n[1] = n[1].length > 1 ? n[1].substr(0, 2) : n[1] + '0';
                    res = n[0] + '.' + n[1];
                }
                return res + tail;
            }
        }

        var s1 = twoDecimal(5);
        console.log('s1+' + s1);
        var s2 = twoDecimal(5.2);
        console.log('s2+' + s2);
        var s3 = twoDecimal(0.232543);
        console.log('s3+' + s3);
        var s4 = twoDecimal('5.232543.099');
        console.log('s4+' + s4);
        var s5 = twoDecimal(NaN);
        console.log('s5+' + s5);
        var s6 = twoDecimal('dskljaf');
        console.log('s6+' + s6);
        var s7 = twoDecimal(Number.MAX_VALUE * 2);
        console.log('s7+' + s7);
        var s8 = twoDecimal(1e100);
        console.log('s8+' + s8);
        var s9 = twoDecimal(Number.MAX_VALUE);
        console.log('s8+' + s9);

输出结果:

如果哪里不对,还请老铁指正 :-) 

原文地址:https://www.cnblogs.com/ariel-zhang/p/7301981.html