Java word to number one

Asked
8 years, 5 months ago

Viewed
26k times

I have seen a lot of algorithms in which you give them a number say «123» and it converts it to One hundred twenty three. But I can’t seem to find something that does the opposite, and the ones I did find only do it up to the number 1000. Can anyone direct me in the correct way as what I could do to create a method that takes «One thousand two hundred and thirty four» and gives back «1234»

Mark Rotteveel's user avatar

asked Nov 15, 2014 at 17:51

Alizoh's user avatar

1

I hope below code will do the job in most of the cases. However some modification might be required as I’ve not tested properly yet.

Assumption:

  1. Positive, negative, plus, minus is not allowed.
  2. Lac, crore is not allowed.
  3. Only English language is supported.

If you need to support first two points, you can very easily do that.

    boolean isValidInput = true;
    long result = 0;
    long finalResult = 0;
    List<String> allowedStrings = Arrays.asList
    (
    "zero","one","two","three","four","five","six","seven",
    "eight","nine","ten","eleven","twelve","thirteen","fourteen",
    "fifteen","sixteen","seventeen","eighteen","nineteen","twenty",
    "thirty","forty","fifty","sixty","seventy","eighty","ninety",
    "hundred","thousand","million","billion","trillion"
    );

    String input="One hundred two thousand and thirty four";

    if(input != null && input.length()> 0)
    {
        input = input.replaceAll("-", " ");
        input = input.toLowerCase().replaceAll(" and", " ");
        String[] splittedParts = input.trim().split("\s+");

        for(String str : splittedParts)
        {
            if(!allowedStrings.contains(str))
            {
                isValidInput = false;
                System.out.println("Invalid word found : "+str);
                break;
            }
        }
        if(isValidInput)
        {
            for(String str : splittedParts)
            {
                if(str.equalsIgnoreCase("zero")) {
                    result += 0;
                }
                else if(str.equalsIgnoreCase("one")) {
                    result += 1;
                }
                else if(str.equalsIgnoreCase("two")) {
                    result += 2;
                }
                else if(str.equalsIgnoreCase("three")) {
                    result += 3;
                }
                else if(str.equalsIgnoreCase("four")) {
                    result += 4;
                }
                else if(str.equalsIgnoreCase("five")) {
                    result += 5;
                }
                else if(str.equalsIgnoreCase("six")) {
                    result += 6;
                }
                else if(str.equalsIgnoreCase("seven")) {
                    result += 7;
                }
                else if(str.equalsIgnoreCase("eight")) {
                    result += 8;
                }
                else if(str.equalsIgnoreCase("nine")) {
                    result += 9;
                }
                else if(str.equalsIgnoreCase("ten")) {
                    result += 10;
                }
                else if(str.equalsIgnoreCase("eleven")) {
                    result += 11;
                }
                else if(str.equalsIgnoreCase("twelve")) {
                    result += 12;
                }
                else if(str.equalsIgnoreCase("thirteen")) {
                    result += 13;
                }
                else if(str.equalsIgnoreCase("fourteen")) {
                    result += 14;
                }
                else if(str.equalsIgnoreCase("fifteen")) {
                    result += 15;
                }
                else if(str.equalsIgnoreCase("sixteen")) {
                    result += 16;
                }
                else if(str.equalsIgnoreCase("seventeen")) {
                    result += 17;
                }
                else if(str.equalsIgnoreCase("eighteen")) {
                    result += 18;
                }
                else if(str.equalsIgnoreCase("nineteen")) {
                    result += 19;
                }
                else if(str.equalsIgnoreCase("twenty")) {
                    result += 20;
                }
                else if(str.equalsIgnoreCase("thirty")) {
                    result += 30;
                }
                else if(str.equalsIgnoreCase("forty")) {
                    result += 40;
                }
                else if(str.equalsIgnoreCase("fifty")) {
                    result += 50;
                }
                else if(str.equalsIgnoreCase("sixty")) {
                    result += 60;
                }
                else if(str.equalsIgnoreCase("seventy")) {
                    result += 70;
                }
                else if(str.equalsIgnoreCase("eighty")) {
                    result += 80;
                }
                else if(str.equalsIgnoreCase("ninety")) {
                    result += 90;
                }
                else if(str.equalsIgnoreCase("hundred")) {
                    result *= 100;
                }
                else if(str.equalsIgnoreCase("thousand")) {
                    result *= 1000;
                    finalResult += result;
                    result=0;
                }
                else if(str.equalsIgnoreCase("million")) {
                    result *= 1000000;
                    finalResult += result;
                    result=0;
                }
                else if(str.equalsIgnoreCase("billion")) {
                    result *= 1000000000;
                    finalResult += result;
                    result=0;
                }
                else if(str.equalsIgnoreCase("trillion")) {
                    result *= 1000000000000L;
                    finalResult += result;
                    result=0;
                }
            }

            finalResult += result;
            result=0;
            System.out.println(finalResult);
        }
    }

answered Nov 15, 2014 at 22:52

Kartic's user avatar

KarticKartic

2,9155 gold badges21 silver badges43 bronze badges

2

package com;

import java.util.HashMap;

public class WordNNumber {

    static HashMap<String, Integer> numbers= new HashMap<String, Integer>();

    static HashMap<String, Integer> onumbers= new HashMap<String, Integer>();
    static HashMap<String, Integer> tnumbers= new HashMap<String, Integer>();

    static {
        numbers.put("zero", 0);
        numbers.put("one", 1);
        numbers.put("two", 2);
        numbers.put("three", 3);
        numbers.put("four", 4);
        numbers.put("five", 5);
        numbers.put("six", 6);
        numbers.put("seven", 7);
        numbers.put("eight", 8);
        numbers.put("nine", 9);
        numbers.put("ten", 10);
        numbers.put("eleven", 11);
        numbers.put("twelve", 12);
        numbers.put("thirteen", 13);
        numbers.put("fourteen", 14);
        numbers.put("fifteen", 15);
        numbers.put("sixteen", 16);
        numbers.put("seventeen", 17);
        numbers.put("eighteen", 18);
        numbers.put("nineteen", 19);


        tnumbers.put("twenty", 20);
        tnumbers.put("thirty", 30);
        tnumbers.put("fourty", 40);
        tnumbers.put("fifty", 50);
        tnumbers.put("sixty", 60);
        tnumbers.put("seventy", 70);
        tnumbers.put("eighty", 80);
        tnumbers.put("ninety", 90);

        onumbers.put("hundred", 100);
        onumbers.put("thousand", 1000);
        onumbers.put("million", 1000000);
        onumbers.put("billion", 1000000000);

        //numbers.put("", );
    }

    public static void main(String args[]){
        String input1="fifty five million twenty three thousand ninety one";
        String input2="fifty five billion three thousand one";
        String input3="fifty five million ninety one";

        wordToNumber(input1);
        wordToNumber(input2);
        wordToNumber(input3);


    }

    private static void wordToNumber(String input) {
        System.out.println("===========nInput string = "+input);
        long sum=0;
        Integer temp=null;
        Integer previous=0;
        String [] splitted= input.toLowerCase().split(" ");


        for(String split:splitted){

            if( numbers.get(split)!=null){
                temp= numbers.get(split);

                sum=sum+temp;

                previous=previous+temp;
            }
            else if(onumbers.get(split)!=null){
                if(sum!=0){
                    sum=sum-previous;
                }
                sum=sum+(long)previous*(long)onumbers.get(split);
                temp=null;
                previous=0;


            }
            else if(tnumbers.get(split)!=null){
                temp=tnumbers.get(split);
                sum=sum+temp;

                previous=temp;
            }

        }

        System.out.println(sum);
    }

}

Andrei T.'s user avatar

Andrei T.

2,4451 gold badge13 silver badges28 bronze badges

answered Apr 4, 2017 at 9:11

Debayan Bhattacharya's user avatar

Okay, I think I’ve gotten something.

There is a variable called ‘debug’, when the number produces doesn’t work like it should please set this to true and do the following things:
1) Give me the string you used and the number you expected
2) Give me the log it produces
3) Be patient

If you want numbers above 1 trillion (which I can’t imagine, but well) please tell me what that number is called ;)

The code:

    boolean debug=true;
    String word="";

    // All words below and others should work
    //word="One thousand two hundred thirty four"; //1234
    //word="Twenty-one hundred thirty one"; //2131
    //word="Forty-three thousand seven hundred fifty one"; //43751
    //word="Nineteen thousand eighty"; // 19080
    //word="five-hundred-forty-three thousand two hundred ten"; //543210
    //word="ninety-eight-hundred-seventy-six thousand"; // 9876000

    // Max:
    word="nine-hundred-ninety-nine trillion nine-hundred-ninety-nine billion nine-hundred-ninety-nine million nine-hundred-ninety-nine thousand nine hundred ninety nine";


    word=word.toLowerCase().trim();

    String oldWord="";
    while(word!=oldWord) {
        oldWord=word;
        word=word.replace("  "," ");
    }

    String[] data=word.split(" ");

    HashMap<String, Long> database=new HashMap<String, Long>();
    database.put("zero", 0L);
    database.put("one", 1L);
    database.put("two", 2L);
    database.put("three", 3L);
    database.put("four", 4L);
    database.put("five", 5L);
    database.put("six", 6L);
    database.put("seven", 7L);
    database.put("eight", 8L);
    database.put("nine", 9L);

    database.put("ten", 10L);
    database.put("hundred", 100L);
    database.put("thousand", 1000L);
    database.put("million", 1000000L);
    database.put("billion", 1000000000L);
    database.put("trillion", 1000000000000L);

    // Exceptional prefixes
    database.put("twen", 2L);
    database.put("thir", 3L);
    database.put("for", 4L);
    database.put("fif", 5L);
    database.put("eigh", 8L);

    // Other exceptions
    database.put("eleven", 11L);
    database.put("twelve", 12L);


    boolean negative=false;
    long sum=0;
    for(int i=0; i<data.length; i+=2) {

        long first=0;
        long second=1;

        try {
            if(data[i].equals("minus")) {
                if(debug) System.out.println("negative=true");
                negative=true;
                i--;
            } else if(data[i].endsWith("ty")) {
                first=database.get(data[i].split("ty")[0])*10;
                i--;
            } else if(data[i].endsWith("teen")) {
                first=database.get(data[i].split("teen")[0])+10;
                if(data.length>i+1)
                    if(database.get(data[i+1])%10!=0)
                        i--;
                    else
                        second=database.get(data[i+1]);
            } else if(data[i].contains("-")){
                String[] moreData=data[i].split("-");

                long a=0;
                long b=0;

                if(moreData[0].endsWith("ty")) {
                    a=database.get(moreData[0].split("ty")[0])*10;
                } else {
                    a=database.get(moreData[0]);
                }

                if(debug) System.out.println("a="+a);

                b=database.get(moreData[1]);
                if(b%10==0)
                    first=a*b;
                else
                    first=a+b;

                if(debug) System.out.println("b="+b);

                if(moreData.length>2) {
                    for(int z=2; z<moreData.length; z+=2) {
                        long d=0;
                        long e=0;

                        if(moreData[z].endsWith("ty")) {
                            d=database.get(moreData[z].split("ty")[0])*10;
                        } else {
                            d=database.get(moreData[z]);
                        }

                        if(debug) System.out.println("d="+d);

                        if(d%100==0) {
                            first*=d;
                            z--;
                        } else {
                            e=database.get(moreData[z+1]);
                            if(e%10==0)
                                first+=d*e;
                            else
                                first+=d+e;
                            if(debug) System.out.println("e="+e);
                        }
                    }
                }

                second=database.get(data[i+1]);

            } else if(word.length()>0){
                first=database.get(data[i]);
                if(data.length>i+1)
                    second=database.get(data[i+1]);
            } else {
                System.err.println("You didn't even enter a word :/");
            }

            if(debug) System.out.println("first="+first);
            if(debug) System.out.println("second="+second);

        } catch(Exception e) {
            System.out.println("[Debug Info, Ignore] Couldn't parse "+i+"["+data[i]+"]");
            e.printStackTrace(System.out);
        }

        sum+=first*second;
    }
    if(negative)
        sum*=-1;

    System.out.println("Result: "+sum);

Let me know if it works and don’t forget to give feedback. (Both positive and negative)
Happy coding :) -Charlie
PS: My native language isn’t English, but this works as I should write numbers. Let me know if it isn’t!

answered Nov 15, 2014 at 19:31

Charlie's user avatar

CharlieCharlie

9681 gold badge7 silver badges26 bronze badges

10

I have done another implementation of the same using HashMap to store the numbers and avoiding if else in a statement.

Assumptions:
Negative numbers not handled

Code:

import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

public class TranslateSentenceTonumber2 {

public static void main(String[] args) {
    initFIRSTTWENTY();

    String sentence1 = "I have twenty thousand twenti two rupees";
    translateNumber(sentence1);
  
    String sentence4 = "one hundred ten thousand";
    translateNumber(sentence4);

    String sentence5 = "one hundred forty seven";
    translateNumber(sentence4 + " " +sentence5);
}

private static HashMap<String, Integer> FIRSTTWENTY;

private static final String SPACES_SPLIT = "\s+";

private static void translateNumber(String playSentence){
    String sentence = playSentence;
    HashMap<String, Long> CALCULATION = new HashMap<>();
    Set<String > ALLOWED = new HashSet<>(FIRSTTWENTY.keySet());
    ALLOWED.add("hundred");
    ALLOWED.add("thousand");
    ALLOWED.add("million");
    if (sentence != null && sentence.length() >0) {
        sentence = sentence.replace("-", " ");
        String [] splittedString = sentence.split(SPACES_SPLIT);
        String continuousString = "";
        int length = splittedString.length;
        for (int i=0; i<length; i++){
            String str  = splittedString[i];
            if (ALLOWED.contains(str.toLowerCase()) && !continuousString.trim().equalsIgnoreCase(str)){
                continuousString = continuousString.trim() + " " + str;
                if (i== length-1){
                    CALCULATION.put(continuousString.trim(), null);
                    continuousString = "";
                }
            }
            if (!ALLOWED.contains(str.toLowerCase()) && !continuousString.trim().isEmpty()) {
                CALCULATION.put(continuousString.trim(), null);
                continuousString = "";
            }
        }

        CALCULATION.replaceAll((c, v) -> calculation(c));

        for(String calc : CALCULATION.keySet()){
            playSentence = playSentence.replace(calc, "" +CALCULATION.get(calc));
        }
        System.out.println(playSentence);
    }
}

private static long calculation(String input){
    long inBetweenCalculation = 0;
    long output = 0;
    if (input != null && !input.isEmpty()) {
        String [] array = input.split(SPACES_SPLIT);
        for (String str: array) {
            if (FIRSTTWENTY.containsKey(str.toLowerCase())) {
                inBetweenCalculation += FIRSTTWENTY.get(str.toLowerCase());
            } else if ("hundred".equalsIgnoreCase(str)) {
                inBetweenCalculation *= 100;
            } else if ("thousand".equalsIgnoreCase(str)) {
                inBetweenCalculation *= 1000;
                output += inBetweenCalculation;
                inBetweenCalculation = 0;
            } else if ("million".equalsIgnoreCase(str)) {
                inBetweenCalculation *= 1000000;
                output += inBetweenCalculation;
                inBetweenCalculation = 0;
            }
        }
        output += inBetweenCalculation;
    }
    return output;
}


private static void initFIRSTTWENTY(){
    FIRSTTWENTY = new HashMap<>();
    FIRSTTWENTY.put("zero", 0);
    FIRSTTWENTY.put("one", 1);FIRSTTWENTY.put("eleven", 11);
    FIRSTTWENTY.put("two", 2);FIRSTTWENTY.put("twelve", 12);
    FIRSTTWENTY.put("three", 3);FIRSTTWENTY.put("thirteen", 13);
    FIRSTTWENTY.put("four", 4);FIRSTTWENTY.put("fourteen", 14);
    FIRSTTWENTY.put("five", 5);FIRSTTWENTY.put("fifteen", 15);
    FIRSTTWENTY.put("six", 6);FIRSTTWENTY.put("sixteen", 16);
    FIRSTTWENTY.put("seven", 7);FIRSTTWENTY.put("seventeen", 17);
    FIRSTTWENTY.put("eight", 8);FIRSTTWENTY.put("eighteen", 18);
    FIRSTTWENTY.put("nine", 9);FIRSTTWENTY.put("nineteen", 19);
    FIRSTTWENTY.put("ten", 10);FIRSTTWENTY.put("twenty", 20);
    FIRSTTWENTY.put("thirty", 30);FIRSTTWENTY.put("forty", 40);
    FIRSTTWENTY.put("fifty", 50);FIRSTTWENTY.put("sixty", 60);
    FIRSTTWENTY.put("seventy", 70);FIRSTTWENTY.put("eighty", 80);
    FIRSTTWENTY.put("ninety", 90);
}
}

Output:

I have 20000 twenti 2 rupees

110000

110147

answered Oct 8, 2020 at 4:42

tpsaitwal's user avatar

tpsaitwaltpsaitwal

4221 gold badge5 silver badges23 bronze badges

Works for lakhs and crores and ignores «and» .Doesn’t handle

  1. Invalid cases like «eight «and» crores».
  2. Inputs like » fifty billion crores»
    boolean isValidInput = true;
    long result = 0;
    long finalResult = 0;
    List<String> allowedStrings = Arrays.asList
    (
    "zero","one","two","three","four","five","six","seven",
    "eight","nine","ten","eleven","twelve","thirteen","fourteen",
    "fifteen","sixteen","seventeen","eighteen","nineteen","twenty",
    "thirty","forty","fifty","sixty","seventy","eighty","ninety",
    "hundred","lakhs","lakh","thousand","crore","crores","and",
    "million","billion","trillion"
    );

    //String input="one hundred";
    String input = String.join(" ", args);
    if(input != null && input.length()> 0)
    {
        input = input.replaceAll("-", " ");
        input = input.toLowerCase().replaceAll(" and", " ");
        String[] splittedParts = input.trim().split("\s+");

        for(String str : splittedParts)
        {
            if(!allowedStrings.contains(str))
            {
                isValidInput = false;
                System.out.println("Invalid word found : "+str);
                break;
            }
        }
        if(isValidInput)
        {
            for(String str : splittedParts)
            {
                String compare=str.toLowerCase();
                switch(compare){
                case "and":break;
                case "zero":result += 0;
                            break;
                case "one":result += 1;
                           break;
                
                case "two":result += 2;
                           break;
                case "three":result += 3;
                           break;
                case "four":result += 4;
                           break; 
                case "five":result += 5;
                           break;  
                case "six":result += 6;
                           break;
                case "seven":result += 7;
                           break;
                case "eight":result += 8;
                           break;
                case "nine":result += 9;
                           break;
                case "ten":result += 10;
                           break;
                case "eleven":result += 11;
                           break;
                case "twelve":result += 12;
                           break;
                case "thirteen":result += 13;
                           break;
                case "fourteen":result += 14;
                           break;
                case "fifteen":result += 15;
                           break;
                case "sixteen":result += 16;
                           break;
                case "seventeen":result += 17;
                           break;
                case "eighteen":result += 18;
                           break;
                case "nineteen":result += 19;
                           break;
                case "twenty":result += 20;
                           break;
                case "thirty":result += 30;
                           break;
                case "forty":result += 40;
                           break;
                case "fifty":result += 50;
                           break;
                case "sixty":result += 60;
                           break;
                case "seventy":result += 70;
                           break;
                case "eighty":result += 80;
                           break;
                case "ninety":result += 90;
                           break;
                case "hundred":result *= 100;
                           break;
                case "thousand":result *= 1000;
                           finalResult += result;
                           result=0;
                           break;
                case "lakh":result *= 100000;
                           finalResult += result;
                           result=0;
                           break;
                case "lakhs":result *= 100000;
                           finalResult += result;
                           result=0;
                           break;
                case "crore":result *= 10000000;
                           finalResult += result;
                           result=0;
                           break;   
                case "crores":result *= 10000000;
                           finalResult += result;
                           result=0;
                           break;
                case "million":result *= 1000000;
                           finalResult += result;
                           result=0;
                           break;
                case "billion":result *= 1000000000;
                           finalResult += result;
                           result=0;
                           break;
                case "trillion":result *= 1000000000000L;
                           finalResult += result;
                           result=0;
                           break;
                }
            }

            finalResult += result;
            result=0;
            System.out.println(finalResult);
        }
    }

Jin Lee's user avatar

Jin Lee

3,13412 gold badges41 silver badges83 bronze badges

answered Mar 3, 2021 at 18:18

meghana anahgem's user avatar

an alternative :)

enum numbers {
    zero,
    one,
    two,
    three,
    four,
    five,
    six,
    eight,
    nine
}

public static String parseNumbers(String text) {

    String out = "";
    for(String s: text.split(" ")) {
        out += numbers.valueOf(s).ordinal();
    }
    return out;
}

answered Sep 16, 2021 at 10:47

kofemann's user avatar

kofemannkofemann

4,1371 gold badge33 silver badges39 bronze badges

I’ve ended up with this solution.
It’s for numbers between zero to one million (can be enhanced easily), can support dash / and / just numbers.

public int parseInt(String number) {
    //Edge cases
    if("one million".equals(number)) return 1000000;
    if("zero".equals(number)) return 0;
    
    String[] splitted = number.split("thousand");
    String hundreds = splitted.length == 1 ? splitted[0].trim() : splitted[1].trim();
    
    int resultRight = calculateTriplet(hundreds);
    
    //X thousand case
    if(splitted.length == 1) {
        if(number.contains("thousand"))
            return resultRight*1000;
        return resultRight;
    }
    
    String thous = splitted[0].trim();
    int resultLeft = calculateTriplet(thous) * 1000;
    
    return resultLeft+resultRight;
}

private int calculateTriplet(String hundreds) {
    String[] triplet = hundreds.split(" |-");
    int result = 0;
    for (int i=0;i<triplet.length;i++) {
        result *= triplet[i].equals("hundred") ? 100 : 1;
        result += upTo19.indexOf(triplet[i]) != -1 ? 
                upTo19.indexOf(triplet[i]) 
                : tens.indexOf(triplet[i]) != -1 ?
                        tens.indexOf(triplet[i])*10 :
                            0;
    }
    return result;
}

  private static final List<String> tens = new ArrayList<String> (Arrays.asList(
            "","ten","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"));

 private static final List<String> upTo19 = new ArrayList<String> (Arrays.asList(
            "","one","two","three","four","five","six","seven","eight","nine", "ten","eleven","twelve","thirteen",
            "fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"));

answered May 30, 2022 at 5:49

Yuval Simhon's user avatar

Yuval SimhonYuval Simhon

1,3642 gold badges16 silver badges34 bronze badges

Best and simple way to print 0 to 99999 numbers to words conversion program

Note: You can also extend more numbers greater than 99999 using same logic.

import java.util.Scanner;
class NumberToWord
{  
    final private static String[]units = {"Zero", "One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten",
    "Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};

    final private static String[]tens = {"","","Twenty ","Thirty ","Forty ","Fifty ","Sixty ","Seventy ","Eighty ","Ninety "};
    public static String convert(int number)
    {
            if(number<0)
            {
                throw new ArithmeticException("Number should be positive.");            
            }
            else if(number<20)
            {
                return (units[number]);
            }   
            else if(number<100)
            {
                return tens[number/10] + ((number % 10 > 0)? convert(number % 10):"");
            }           
            else if(number<1000)
            {
                return units[number/100] + " hundred" + ((number%100>0)? " and " + convert(number%100):"");
            }           
            else if(number<20000)
            {
                return  units[number/1000] + " Thousand " + ((number%1000>0)? convert(number%1000):"");
            }           
                return tens[number/10000] + ((number%10000>0)? convert(number%10000):"Thousand" );      
    }   

    public static void main(String[] args) 
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number between 0 to 99999: ");
        int num = sc.nextInt();
        System.out.println(convert(num));   
    }    
}

Thank you for reading!!

answered Jul 27, 2016 at 14:39

Siddhesh's user avatar

2

Here is some code that I came up with when trying to solve the same problem. Keep in mind that I am not a professional and do not have insane amounts of experience. It is not slow, but I’m sure it could be faster/cleaner/etc. I used it in converting voice recognized words into numbers for calculation in my own «Jarvis» a la Iron Man. It can handle numbers under 1 billion, although it could easily be expanded to include much higher magnitudes at the cost of very little time.

public static final String[] DIGITS = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
public static final String[] TENS = {null, "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
public static final String[] TEENS = {"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
public static final String[] MAGNITUDES = {"hundred", "thousand", "million", "point"};
public static final String[] ZERO = {"zero", "oh"};

public static String replaceNumbers (String input) {
    String result = "";
    String[] decimal = input.split(MAGNITUDES[3]);
    String[] millions = decimal[0].split(MAGNITUDES[2]);

    for (int i = 0; i < millions.length; i++) {
        String[] thousands = millions[i].split(MAGNITUDES[1]);

        for (int j = 0; j < thousands.length; j++) {
            int[] triplet = {0, 0, 0};
            StringTokenizer set = new StringTokenizer(thousands[j]);

            if (set.countTokens() == 1) { //If there is only one token given in triplet
                String uno = set.nextToken();
                triplet[0] = 0;
                for (int k = 0; k < DIGITS.length; k++) {
                    if (uno.equals(DIGITS[k])) {
                        triplet[1] = 0;
                        triplet[2] = k + 1;
                    }
                    if (uno.equals(TENS[k])) {
                        triplet[1] = k + 1;
                        triplet[2] = 0;
                    }
                }
            }


            else if (set.countTokens() == 2) {  //If there are two tokens given in triplet
                String uno = set.nextToken();
                String dos = set.nextToken();
                if (dos.equals(MAGNITUDES[0])) {  //If one of the two tokens is "hundred"
                    for (int k = 0; k < DIGITS.length; k++) {
                        if (uno.equals(DIGITS[k])) {
                            triplet[0] = k + 1;
                            triplet[1] = 0;
                            triplet[2] = 0;
                        }
                    }
                }
                else {
                    triplet[0] = 0;
                    for (int k = 0; k < DIGITS.length; k++) {
                        if (uno.equals(TENS[k])) {
                            triplet[1] = k + 1;
                        }
                        if (dos.equals(DIGITS[k])) {
                            triplet[2] = k + 1;
                        }
                    }
                }
            }

            else if (set.countTokens() == 3) {  //If there are three tokens given in triplet
                String uno = set.nextToken();
                String dos = set.nextToken();
                String tres = set.nextToken();
                for (int k = 0; k < DIGITS.length; k++) {
                    if (uno.equals(DIGITS[k])) {
                        triplet[0] = k + 1;
                    }
                    if (tres.equals(DIGITS[k])) {
                        triplet[1] = 0;
                        triplet[2] = k + 1;
                    }
                    if (tres.equals(TENS[k])) {
                        triplet[1] = k + 1;
                        triplet[2] = 0;
                    }
                }
            }

            else if (set.countTokens() == 4) {  //If there are four tokens given in triplet
                String uno = set.nextToken();
                String dos = set.nextToken();
                String tres = set.nextToken();
                String cuatro = set.nextToken();
                for (int k = 0; k < DIGITS.length; k++) {
                    if (uno.equals(DIGITS[k])) {
                        triplet[0] = k + 1;
                    }
                    if (cuatro.equals(DIGITS[k])) {
                        triplet[2] = k + 1;
                    }
                    if (tres.equals(TENS[k])) {
                        triplet[1] = k + 1;
                    }
                }
            }
            else {
                triplet[0] = 0;
                triplet[1] = 0;
                triplet[2] = 0;
            }

            result = result + Integer.toString(triplet[0]) + Integer.toString(triplet[1]) + Integer.toString(triplet[2]);
        }
    }

    if (decimal.length > 1) {  //The number is a decimal
        StringTokenizer decimalDigits = new StringTokenizer(decimal[1]);
        result = result + ".";
        System.out.println(decimalDigits.countTokens() + " decimal digits");
        while (decimalDigits.hasMoreTokens()) {
            String w = decimalDigits.nextToken();
            System.out.println(w);

            if (w.equals(ZERO[0]) || w.equals(ZERO[1])) {
                result = result + "0";
            }
            for (int j = 0; j < DIGITS.length; j++) {
                if (w.equals(DIGITS[j])) {
                    result = result + Integer.toString(j + 1);
                }   
            }

        }
    }

    return result;
}

Input must be in grammatically correct syntax, otherwise it will have issues (create a function to remove «and»). A string input of «two hundred two million fifty three thousand point zero eight five eight oh two» returns:

two hundred two million fifty three thousand point zero eight five eight oh two
202053000.085802
It took 2 milliseconds.

Очень часто бывает следующая задача: конвертировать строку в числовой тип. В Java это можно сделать разными способами. Главное – учитывать максимальную размерность данных и точность (для дробных чисел).

Преобразование строки в целое число

Для конвертации строк в целые числа есть методы Integer.parseInt и Long.parseLong для конвертации в типы int и long, соответственно.

Простой способ получить int из строки:

int a1 = Integer.parseInt("123");
System.out.println(a1);

Примечание: метод Integer.parseInt корректно преобразует числа, входящие в диапазон типа int (-2147483648..2147483647). Если число выходит за эти границы или содержит недопустимые символы, будет выброшено исключение NumberFormatException:

int a2 = Integer.parseInt("3000000000"); // NumberFormatException
int a3 = Integer.parseInt("123abc"); // NumberFormatException

Если вам нужны числа большей размерности, чем int, воспользуйтесь методом Long.parseLong:

long b1 = Long.parseLong("3000000000");
System.out.println(b1);

Например, можно использовать такой утилитарный метод, который при невозможности корректно распарсить строку вернёт ноль:

public static long stringToLong(String s) {
    try {
        return Long.parseLong(s);
    } catch (NumberFormatException e) {
        return 0;
    }
}

Преобразование строки в дробное число

Для преобразования строк в дробные числа можно воспольоваться методами Float.parseFloat и Double.parseDouble, которые производят числа типов float и double, соответственно:

float f1 = Float.parseFloat("123.45");
System.out.println(f1);

double d1 = Double.parseDouble("123.45");
System.out.println(d1);

Стоит заметить, что лучше пользоваться double вместо float из-за повышенной точности double.

Преобразование больших чисел

Если вам не хватает размерности для хранения чисел типах long и double, вы можете использовать BigInteger и BigDecimal:

System.out.println(new BigInteger("9223372036854775807000"));
System.out.println(new BigDecimal("9.223372036854776777E21"));

Здесь не получится воспользоваться преобразованием в int из-за выхода за размеры int; получится преобразовать в double, но с потерей точности.

Заключение

В данной статье мы описали стандартные методы преобразования строки в число. При выборе метода нужно учитывать размерность типов, к которому приводится число.

Теги: java, string, типы данных, преобразование строки в число, преобразование числа в строку

В некоторых случаях при программировании на Java нам нужно выполнить преобразование строки в число или числа в строку. Это бывает, если мы имеем величину определённого типа и желаем присвоить эту величину переменной другого типа. Преобразования типов в Java осуществляются разными способами, давайте рассмотрим наиболее популярные из них.

JavaSpec_970x90-20219-e8e90f.png

Как преобразовать строку в число в Java?

Речь идёт о преобразовании String to Number. Обратите внимание, что в наших примерах, с которыми будем работать, задействована конструкция try-catch. Это нужно нам для обработки ошибки в том случае, когда строка содержит другие символы, кроме чисел либо число, которое выходит за рамки диапазона предельно допустимых значений указанного типа. К примеру, строку «onlyotus» нельзя перевести в тип int либо в другой числовой тип, т. к. при компиляции мы получим ошибку. Для этого нам и нужна конструкция try-catch.

Преобразуем строку в число Java: String to byte

Выполнить преобразование можно следующими способами:

C помощью конструктора:

    try {
        Byte b1 = new Byte("10");
        System.out.println(b1);
    } catch (NumberFormatException e) {
        System.err.println("Неправильный формат строки!");
    }

С помощью метода valueOf класса Byte:

    String str1 = "141";
    try {
        Byte b2 = Byte.valueOf(str1);
        System.out.println(b2);
    } catch (NumberFormatException e) {
        System.err.println("Неправильный формат строки!");
    }

С помощью метода parseByte класса Byte:

    byte b = 0;
    String str2 = "108";
    try {
        b = Byte.parseByte(str2);
        System.out.println(b);
    } catch (NumberFormatException e) {
        System.err.println("Неправильный формат строки!");
    }

А теперь давайте посмотрим, как выглядит перевод строки в массив байтов и обратно в Java:

    String str3 = "20150";
    byte[] b3 = str3.getBytes();
    System.out.println(b3);

    //массив байтов переводится обратно в строку 
    try {
      String s = new String(b3, "cp1251");
      System.out.println(s);
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }

Преобразуем строку в число в Java: String to int

Здесь, в принципе, всё почти то же самое:

Используем конструктор:

    try { 
        Integer i1 = new Integer("10948");
        System.out.println(i1);
    }catch (NumberFormatException e) {  
        System.err.println("Неправильный формат строки!");  
    }   

Используем метод valueOf класса Integer:

    String str1 = "1261";
    try {
        Integer i2 = Integer.valueOf(str1);
        System.out.println(i2);    
    }catch (NumberFormatException e) {  
        System.err.println("Неправильный формат строки!");  
    }  

Применяем метод parseInt:

    int i3 = 0;
    String str2 = "203955";
    try {
        i3 = Integer.parseInt(str2);
        System.out.println(i3);  
    } catch (NumberFormatException e) {  
        System.err.println("Неправильный формат строки!");  
    }     

Аналогично действуем и для других примитивных числовых типов данных в Java: short, long, float, double, меняя соответствующим образом названия классов и методов.

Как преобразовать число в строку в Java?

Теперь поговорим о преобразовании числа в строку (Number to String). Рассмотрим несколько вариантов:

1. Преобразование int to String в Java:

   int i = 53;
   String str = Integer.toString(i);
   System.out.println(str);   

2. Преобразование double to String в Java:

   double  i = 31.6e10;
   String str = Double.toString(i);
   System.out.println(str);  

3. Преобразуем long to String в Java:

   long  i = 3422222;
   String str = Long.toString(i);
   System.out.println(str);         

4. Преобразуем float to String в Java:

   float  i = 3.98f;
   String str = Float.toString(i);
   System.out.println(str);      

JavaSpec_970x550-20219-a74b18.png

Java String to Int – How to Convert a String to an Integer

String objects are represented as a string of characters.

If you have worked in Java Swing, it has components such as JTextField and JTextArea which we use to get our input from the GUI. It takes our input as a string.

If we want to make a simple calculator using Swing, we need to figure out how to convert a string to an integer. This leads us to the question – how can we convert a string to an integer?

In Java, we can use Integer.valueOf() and Integer.parseInt() to convert a string to an integer.

1. Use Integer.parseInt() to Convert a String to an Integer

This method returns the string as a primitive type int. If the string does not contain a valid integer then it will throw a NumberFormatException.

So, every time we convert a string to an int, we need to take care of this exception by placing the code inside the try-catch block.

Let’s consider an example of converting a string to an int using Integer.parseInt():

        String str = "25";
        try{
            int number = Integer.parseInt(str);
            System.out.println(number); // output = 25
        }
        catch (NumberFormatException ex){
            ex.printStackTrace();
        }

Let’s try to break this code by inputting an invalid integer:

     	String str = "25T";
        try{
            int number = Integer.parseInt(str);
            System.out.println(number);
        }
        catch (NumberFormatException ex){
            ex.printStackTrace();
        }

As you can see in the above code, we have tried to convert 25T to an integer. This is not a valid input. Therefore, it must throw a NumberFormatException.

Here’s the output of the above code:

java.lang.NumberFormatException: For input string: "25T"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:580)
	at java.lang.Integer.parseInt(Integer.java:615)
	at OOP.StringTest.main(StringTest.java:51)

Next, we will consider how to convert a string to an integer using the Integer.valueOf() method.

This method returns the string as an integer object. If you look at the Java documentation, Integer.valueOf() returns an integer object which is equivalent to a new Integer(Integer.parseInt(s)).

We will place our code inside the try-catch block when using this method. Let us consider an example using the Integer.valueOf() method:

        String str = "25";
        try{
            Integer number = Integer.valueOf(str);
            System.out.println(number); // output = 25
        }
        catch (NumberFormatException ex){
            ex.printStackTrace();
        }

Now, let’s try to break the above code by inputting an invalid integer number:

        String str = "25TA";
        try{
            Integer number = Integer.valueOf(str);
            System.out.println(number); 
        }
        catch (NumberFormatException ex){
            ex.printStackTrace();
        }

Similar to the previous example, the above code will throw an exception.

Here’s the output of the above code:

java.lang.NumberFormatException: For input string: "25TA"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:580)
	at java.lang.Integer.valueOf(Integer.java:766)
	at OOP.StringTest.main(StringTest.java:42)

We can also create a method to check if the passed-in string is numeric or not before using the above mentioned methods.

I have created a simple method for checking whether the passed-in string is numeric or not.

public class StringTest {
    public static void main(String[] args) {
        String str = "25";
        String str1 = "25.06";
        System.out.println(isNumeric(str));
        System.out.println(isNumeric(str1));
    }

    private static boolean isNumeric(String str){
        return str != null && str.matches("[0-9.]+");
    }
}

The output is:

true
true

The isNumeric() method takes a string as an argument. First it checks if it is null or not. After that we use the matches() method to check if it contains digits 0 to 9 and a period character.

This is a simple way to check numeric values. You can write or search Google for more advanced regular expressions to capture numerics depending on your use case.

It is a best practice to check if the passed-in string is numeric or not before trying to convert it to integer.

Thank you for reading.

Post image by 🇸🇮 Janko Ferlič on Unsplash

You can connect with me on Medium.

Happy Coding!



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Introduction

Converting a String to an int, or its respective wrapper class Integer, is a common and simple operation. The same goes for the other way around, converting a Integer to String.

There are multiple ways to achieve this simple conversion using methods built-in to the JDK.

Converting String to Integer

For converting String to Integer or int, there are four built-in approaches. The wrapper class Integer provides a few methods specifically for this use — parseInt(), valueOf() and decode(), although we can also use its constructor and pass a String into it.

These three methods have different return types:

  • parseInt()— returns primitive int.
  • valueOf() — returns a new or cached instance of Integer
  • decode() — returns a new or cached instance of Integer

That being said, it’s valid to raise a question:

«What’s the difference between valueOf() and decode() then?

The difference is that decode() also accepts other number representations, other than regular decimal — hex digits, octal digits, etc.

Note: It’s better practice to instantiate an Integer with the help of the valueOf() method rather than relying on the constructor. This is because the valueOf() method will return a cached copy for any value between -128 and 127 inclusive, and by doing so will reduce the memory footprint.

Integer.parseInt()

The parseInt() method ships in two flavors:

  • parseInt(String s) — Accepting the String we’d like to parse
  • parseInt(String s, int radix) — Accepting the String as well as the base of the numeration system

The parseInt() method converts the input String into a primitive int and throws a NumberFormatException if the String cannot be converted:

String string1 = "100";
String string2 = "100";
String string3 = "Google";
String string4 = "20";

int number1 = Integer.parseInt(string1);
int number2 = Integer.parseInt(string2, 16); 
int number3 = Integer.parseInt(string3, 32); 
int number4 = Integer.parseInt(string4, 8); 

System.out.println("Parsing String "" + string1 + "": " + number1);
System.out.println("Parsing String "" + string2 + "" in base 16: " + number2);
System.out.println("Parsing String "" + string3 + "" in base 32: " + number3);
System.out.println("Parsing String "" + string4 + "" in base 8: " + number4);

Running this piece of code will yield:

Parsing String "100": 100
Parsing String "100" in base 16: 256
Parsing String "Google" in base 32: 562840238
Parsing String "20" in base 8: 16

Integer.valueOf()

The valueOf() ships in three flavors:

  • valueOf(String s) — Accepts a String and parses it into an Integer
  • valueOf(int i) — Accepts an int and parses it into an Integer
  • valueOf(String s, int radix) — Accepts a String and returns an Integer representing the value and then parses it with the given base

The valueOf() method, unlike the parseInt() method, returns an Integer instead of a primitive int and also throws a NumberFormatException if the String cannot be converted properly and only accepts decimal numbers:

int i = 10;
String string1 = "100";
String string2 = "100";
String string3 = "Google";
String string4 = "20";

int number1 = Integer.valueOf(i);
int number2 = Integer.valueOf(string1); 
int number3 = Integer.valueOf(string3, 32); 
int number4 = Integer.valueOf(string4, 8); 

System.out.println("Parsing int " + i + ": " + number1);
System.out.println("Parsing String "" + string1 + "": " + number2);
System.out.println("Parsing String "" + string3 + "" in base 32: " + number3);
System.out.println("Parsing String "" + string4 + "" in base 8: " + number4);

Running this piece of code will yield:

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Parsing int 10: 10
Parsing String "100": 100
Parsing String "Google" in base 32: 562840238
Parsing String "20" in base 8: 16

Integer.decode()

The decode() method accepts a single parameter and comes in one flavor:

  • decode(String s) — Accepts a String and decodes it into an Integer

The decode() method accepts decimal, hexadecimal and octal numbers, but doesn’t support binary:

String string1 = "100";
String string2 = "50";
String string3 = "20";

int number1 = Integer.decode(string1);
int number2 = Integer.decode(string2); 
int number3 = Integer.decode(string3); 

System.out.println("Parsing String "" + string1 + "": " + number2);
System.out.println("Parsing String "" + string2 + "": " + number2);
System.out.println("Parsing String "" + string3 + "": " + number3);

Running this piece of code will yield:

Parsing String "100": 50
Parsing String "50": 50
Parsing String "20": 20

Conclusion

We’ve covered one of the fundamental topics of Java and common problem developers face — Converting a String to an Integer or int using tools shipped with the JDK.

The challenge

We need a function that can transform a string into a number. What ways of achieving this do you know?

Note: Don’t worry, all inputs will be strings, and every string is a perfectly valid representation of an integral number.

Examples

stringToNumber("1234") == 1234
stringToNumber("605" ) == 605
stringToNumber("1405") == 1405
stringToNumber("-7"  ) == -7

Test cases

import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class StringToNumberTest {   
    @Test
    public void test1(){
      assertEquals("stringToNumber(1234)", 1234 , StringToNumber.stringToNumber("1234"));
    }
    @Test
    public void test2(){
      assertEquals("stringToNumber(605)", 605 , StringToNumber.stringToNumber("605"));
    }
    @Test
    public void test3(){
      assertEquals("stringToNumber(1405)", 1405 , StringToNumber.stringToNumber("1405"));
    }
    @Test
    public void test4(){
      assertEquals("stringToNumber(-7)", -7 , StringToNumber.stringToNumber("-7"));
    }
    @Test
    public void test5(){
      for(int i = 0; i < 100; ++i) {
        int t = (int)Math.round(Math.random() * 500000);
        assertEquals("stringToNumber(" + t + ")", t , StringToNumber.stringToNumber(Integer.toString(t)));
      }
    }
}

The solution in Java

Option 1 (using parseInt):

public class StringToNumber {
  public static int stringToNumber(String str) {

    return Integer.parseInt(str);

  }
}

Option 2 (using valueOf):

public class StringToNumber {
  public static int stringToNumber(String str) {

    return Integer.valueOf(str);

  }
}

It may be good practice to go a step further and sanity check the output:

public class StringToNumber {
  public static int stringToNumber(String str) {

    try {

      return Integer.parseInt(str);

    } catch (NumberFormatException NFE) {

      throw NFE;

    }

  }
}

How to Convert String to int in Java – The following article will let you know the complete information about string to int java, in case if you have any doubts do let me know.

We have different ways to convert a String to int in Java

  • Integer.parseInt()
  • Integer.valueOf()
  • Integer.parseUnsignedInt()

Our own logic equivalent to – Integer.parseInt()

  • Integer.decode()
  • Integer() constructor

Etc..

String To Int Java

Integer.parseInt() – How It Works:

Syntax1 – int parseInt(String);

Example:

Integer.parseInt(+234); will result in 234

Integer.parseInt(234); will result in 234

It converts the given String into an integer. Suppose we give a String “234” as argument to the method, then it returns the integer 234. As this is a static method, we can invoke this using its class name.

Example:

int a=25;

int b=Integer.parseInt(234);

int c=a+b;

System.out.println(c); //will print 259

Algorithm for converting string to int without built-in method:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

static int ourMethod(String s)

{

int n=0,mul=1,len=s.length();

if(len==0)

throw new NumberFormatException();

for(int i=0;i<len;i++)

{

int d=s.charAt(i);

if(i==0)

if(d==43)

continue;

else if(d==45)

{

mul=1;

continue;

}

d-=48;

if(d<0 || d>9)

throw new NumberFormatException(s);

n=n*10+d;

}

n*=mul;

return n;

}

Implementation:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

class StringToInt

{

  public static void  main(String args[])

   {

     int x=StringToInt.ourMethod(args[0]);//args[0] is taking input from command line

     System.out.println(«x=»+x);

     System.out.println(«x+1=»+(x+1));

   }

  static int ourMethod(String s)

  {

int n=0,mul=1,len=s.length();

  if(len==0)

          {

             throw new NumberFormatException();

          }

          for(int i=0;i<len;i++)

          {

int d=s.charAt(i);

                if(i==0)

                {

                     if(d==43)

                     {

                         continue;

     }

                     else if(d==45)

     {

         mul=1;

         continue;

     }

                }

               d-=48;

               if(d<0 || d>9)

       {

                  throw new NumberFormatException(s);

       }

               n=n*10+d;

  }

          n*=mul;

  return n;

   }

}

Output:

javac StringToint.java

java StringToint 234

x=234

x+1=235

Integer.decode() – How It Works

An empty String or a String that contains non-digits will result in Number Format Exception.

Ex:    

“234A”, “34.54”, “smile”, “”, etc.

Syntax2:               int parseInt(String,int);

This is similar to normal parseInt(), but it takes an integer as second argument and this argument represents the radix of the content in the input String.

Suppose we want to convert an octal number (which is in String format) into its equivalent decimal integer then the second argument should be 8.

Similarly, if we want a hexa-decimal String to its decimal number then the second argument should be 16.

Eg:            Integer.parseInt(“234”,10);  will result in 234

                  ===>  2*(10^2)+3*(10^1)+4*(10^0)

                  ===>  (2*100)+(3* 10)+(4*1)

                  ===>  200+30+4

                  ===>    234

Implementation:

Example:

Integer.parseInt(234,8);will result in 156

2*(8^2)+3*(8^1)+4*(8^0)

(2*64)+(3* 8)+(4*1)

128+24+4

156

 Integer.parseInt(“234”,2);  will result in NumberFormatException as allowed digits in binary(2) number                        system are 0 and 1 only.

 Integer.parseInt(“789”,8);  will result in NumberFormatException as allowed digits in octal(8) number                           system are from 0 to 7 only

string to int java – Integer.valueOf()

It can also be used similar to Integer.parseInt() to convert a String to int. This method also has an overloaded method to take an int (radix) as second argument where as the first argument is a String.

Integer.parseInt() returns the result as a basic (primitive) int type where as Integer.valueOf() returns the result an Integer object.

Example:       

  • Integer.valueOf(“234”); will give 234 as Integer object
  • Integer.valueOf(“412”); will give 412 as Integer object
  • Integer.valueOf(“234”,8); will give 156 as Integer object
  • Integer.valueOf(“234”,16); will give 564 as Integer object

Integer.parseUnsignedInt()

This is also similar to Integer.valueOf() and Integer.parseInt() but it can work on positive values only.

Example:         

  • Integer.parseUnsignedInt(“874”); returns 874         
  • Integer.parseUnsignedInt(“+874”); returns 874          
  • Integer.parseUnsignedInt(“-874”); raises NumberFormatException

Algorithm:

Syntax: Integer decode(String);

This method converts the given string into an int and returns an Integer object.

Example:

Integer num=Integer.decode(23);

System.out.println(num+2);   // will print 25

The decode() method can assume the type (decimal, octal, hexadecimal…) of the value and makes the conversion accordingly. In computer parlance, a number preceded by 0 is treated as octal and a number

Example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

Integer.decode(234); results in 234

Integer.decode(0234); results in 156

Integer.decode(0x234); results in 564

Integer.decode(+234); results in 234

Integer.decode(234); results in 234

Integer.decode(234A); results in NumberFormatException

Integer.decode(twenty); results in NumberFormatException

Integer.decode(0xabc); results in 2748

Integer.decode(0x123);  results in 2

Integer.decode(0999); results in NumberFormatException

Convert String To int java – Integer()

The class Integer has several constructor and one of them receives a String as argument. By using this, we can convert a String to Integer object. Once we have an integer object, we can convert it to an int (primitive) type.

Example:

String s=«234»;

Integer num=new Integer(s);

System.out.println(num+2);  //will print 236

If you have any doubts related to Convert Java String To Int do leave a comment here.

Contents

  • 1. Introduction
  • 2. Integer.parseInt()
  • 3. Integer.valueOf()
  • 4. Integer.decode()
  • 5. Convert Large Values into Long
  • 6. Use BigInteger for Larger Numbers
  • 7. Parse for Numbers Within Text
  • Summary
    • See Also

1. Introduction

There are several ways of converting a String to an integer in Java. We present a few of them here with a discussion of the pros and cons of each.

2. Integer.parseInt()

Integer.parseInt(String) can parse a string and return a plain int value. The string value is parsed assuming a radix of 10. The string can contain “+” and “-” characters at the start to indicate a positive or negative number.

int value = Integer.parseInt("25"); // returns 25

int value = Integer.parseInt("-43"); // return -43

int value = Integer.parseInt("+9061"); // returns 9061

Illegal characters within the string (including period “.“) result in a NumberFormatException. Additionally a string containing a number larger than Integer.MAX_VALUE (231 - 1) also result in a NumberFormatException.

// throws NumberFormatException -- contains "."
int value = Integer.parseInt("25.0");

// throws NumberFormatException -- contains text
int value = Integer.parseInt("93hello");

// throws NumberFormatException -- too large
int value = Integer.parseInt("2367423890");

To explicitly specify the radix, use Integer.parseInt(String,int) and pass the radix as the second argument.

// returns 443
int value = Integer.parseInt("673", 8);

// throws NumberFormatException -- contains character "9" not valid for radix 8
int value = Integer.parseInt("9061", 8);

// returns 70966758 -- "h" and "i" are valid characters for radix 20.
int value = Integer.parseInt("123aghi", 20);

3. Integer.valueOf()

The static method Integer.valueOf() works similar to Integer.parseInt() with the difference that the method returns an Integer object rather than an int value.

// returns 733
Integer value = Integer.valueOf("733");

Use this method when you need an Integer object rather than a bare int. This method invokes Integer.parseInt(String) and creates an Integer from the result.

4. Integer.decode()

For parsing an integer starting with these prefixes: “0” for octal, “0x”, “0X” and “#” for hex, you can use the method Integer.decode(String). An optional “+” or “-” sign can precede the number. Al the following formats are supported by this method:

Signopt DecimalNumeral
Signopt 0x HexDigits
Signopt 0X HexDigits
Signopt # HexDigits
Signopt 0 OctalDigits

As with Integer.valueOf(), this method returns an Integer object rather than a plain int. Some examples follow:

// returns 53
Integer value = Integer.decode("0x35");

// returns 1194684
Integer value = Integer.decode("#123abc');

// throws NumberFormatException -- value too large
Integer value = Integer.decode("#123abcdef");

// returns -231
Integer value = Integer.decode("-0347");

5. Convert Large Values into Long

When the value being parsed does not fit in an integer (231-1), a NumberFormatException is thrown. In these cases, you can use analogous methods of the Long class: Long.parseLong(String), Long.valueOf(String) and Long.decode(String). These work similar to their Integer counterparts but return a Long object (or a long in the case of Long.parseLong(String)). The limit of a long is Long.LONG_MAX (defined to be 263-1).

// returns 378943640350
long value = Long.parseLong("378943640350");

// returns 3935157603823
Long value = Long.decode("0x39439abcdef");

6. Use BigInteger for Larger Numbers

Java provides another numeric type: java.math.BigInteger with an arbitrary precision. A disadvantage of using BigInteger is that common operations like adding, subtracting, etc require method invocation and cannot be used with operators like “+“, “-“, etc.

To convert a String to a BigInteger, just use the constructor as follows:

BigInteger bi = new BigInteger("3489534895489358943");

To specify a radix different than 10, use a different constructor:

BigInteger bi = new BigInteger("324789045345498589", 12);

7. Parse for Numbers Within Text

To parse for numbers interspersed with arbitrary text, you can use the java.util.Scanner class as follows:

String str = "hello123: we have a 1000 worlds out there.";
Scanner scanner = new Scanner(str).useDemiliter("\D+");
while (s.hasNextInt())
  System.out.printf("(%1$d) ", s.nextInt());
// prints "(123) (1000)"

This method offers a powerful way of parsing for numbers, although it comes with the expense of using a regular expression scanner.

Summary

To summarize, there are various methods of converting a string to an int in java.

  • Integer.parseInt() is the simplest and returns an int.
  • Integer.valueOf() is similar but returns an Integer object.
  • Integer.decode() can parse numbers starting with “0x” and “0” as hex and octal respectively.
  • For larger numbers, use the corresponding methods in the Long class.
  • And for arbitrary precision integers, use the BigInteger class.
  • Finally, to parse arbitrary text for numbers, we can use the java.util.Scanner class with a regular expression.

Like this post? Please share to your friends:
  • Java word for number
  • Javascript if word is in string
  • Java to excel macro
  • Javascript for excel export
  • Java split one word