Java 字符串转数字

字符串转数字,全为数字不包含异常的字符,昨天去面试了,然后问了一个一个简单的东西就是下面这个,写起来没有难度,但是好多细节没注意到,
来回改什么的也写了好几遍,今天就记录一下


public static double parseString(String str) {
        int count = '0';//忘记了ASCII码数字之间相差多少 用'0' - 0 算之间差多少 然后每次用当前字符去减这个count
        if (null == str || "".equals(str))
        return 0;

        double value = 0;
        char[] chs = str.toCharArray();
        for (int i = 1; i < chs.length; i++) {//从1开始最后再判断正负
        if (chs[i] == '.') {//如果是小数,单独处理
        i++;
        value /= Math.pow(10, chs.length - i + 1 );
        for (int j = 0; i < chs.length; i++) {
        value += (chs[i] - count) * Math.pow(Math.pow(0.1,1), ++j);
        }
        break;
        }

        value += (chs[i] - count) * Math.pow(10, chs.length - 1 - i);
        }
        if (chs[0] == '-')
        value *= -1;
        else
        value += (chs[0] - count) * Math.pow(10, chs.length - 1);

        return value;
        }
public static void main(String[] args) {
        double value = parseString("-235678900765");
        System.out.println(value);
        value = parseString("2346424");
        System.out.println(value);
        value = parseString("-12");
        System.out.println(value);
        value = parseString("5678900765");
        System.out.println(value);
        value = parseString("-235765");
        System.out.println(value);

        value = parseString("-235765.123");
        System.out.println(value);
        }

 

猜你喜欢

转载自www.cnblogs.com/wangnanhui/p/9109422.html