Turns a string into an int using a given radix. - Java java.lang

Java examples for java.lang:String Parse

Description

Turns a string into an int using a given radix.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String s = "123";
        int radix = 4;
        System.out.println(parseIntRadix(s, radix));
    }/*w w w  .  j  a v a2s.co  m*/

    /** Turns a string into an int using a given radix.
     * @param s the string to convert
     * @param radix radix to use
     * @return the int value
     */
    public static Number parseIntRadix(String s, int radix) {
        if (s == null)
            return Double.NaN;

        s = s.trim();
        if (s.length() == 0)
            return Double.NaN;

        int firstDigit = -1;
        int i = 0;
        if (s.charAt(0) == '-')
            i = 1;
        // Find first non-digit.
        for (; i < s.length(); i++) {
            if (Character.digit(s.charAt(i), radix) == -1)
                break;
        }

        try {
            // Remember: all numbers in JS are 64-bit
            return Long.parseLong(s.substring(0, i), radix);
        } catch (Exception e) {
            return Double.NaN;
        }
    }
}

Related Tutorials