1. 程式人生 > 其它 >正整數的字串轉數字(java)

正整數的字串轉數字(java)

正整數的字串轉數字(java)

由部分BigDecimal原始碼改編而來

(public BigDecimal(char[] in, int offset, int len, MathContext mc){})

public static void main(String[] args) {
        //正整數的字串轉數字
        String num1="001234";
        System.out.println("排除前置0: "+strToNum(num1));
        //排除前置0: 1234
        String num2="1234";
        System.out.println(
"正常轉換: "+strToNum(num2)); //正常轉換: 1234 String num3="1230kk4"; System.out.println("排除非數字字元: "+strToNum(num3)); //排除非數字字元: 12304 String num4="+12304"; System.out.println("排除前置+: "+strToNum(num4)); //排除前置+: 12304 } private static int strToNum(String str) {
char[] chars = str.toCharArray(); int off = 0; int val = 0; for (int i = 0; i < chars.length; i++) { char c = chars[i]; if (c == '0' && off == 0) { continue; } int suf = c - '0'; if (suf >= 0 && suf <= 9) { val
= val * 10 + suf; off++; } } return val; }