Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a real string integer (e.g. "thirty five") to integer [duplicate]

Tags:

java

Is there a way to convert an English string representation of an integer (e.g. "one hundred eighty") to an integer? As expected Integer.parseInt("thirty five") threw a NumberFormatException. Is there a built in function in Java to do this?

like image 989
Phoeniyx Avatar asked May 09 '26 07:05

Phoeniyx


1 Answers

No.

No, there is no built-in functionality to achieve this.

1. Approach: HashMap

You can use a HashMap to store the String, Integer pair (e.g.: "twenty" and 20).

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

numbers.put("one", 1);
numbers.put("two", 2);

...

numbers.put("nine", 9);
numbers.put("ten", 10);
numbers.put("eleven", 11);

...

numbers.put("twenty", 20);
numbers.put("thirty", 30);

...

Then you can simply parse it via numbers.get(..) and add that number to your resulting number.

public int getNumber(String str)
{
   int number = 0;
   String[] parts = str.split(" ");

   for (String number : parts)
   {
        if (numbers.contains(number)
        {
            number += parts.get(number);
        }
   } 

   return number;
}

2. Approach: ArrayList

You can create an ArrayList like

ArrayList<String> numbers = new ArrayList<String>;

numbers.add("zero");
numbers.add("one");

...

numbers.add("eight");
numbers.add("nine");    
numbers.add("ten");

...

Then you could build your own function to parse a String to those numbers by looking them up in this ArrayList (their index is the resulting number).

public int getNumber(String str)
{
   int number = 0;
   String[] parts = str.split(" ");

   for (String number : parts)
   {
        if (numbers.contains(number)
        {
            number += parts.indexof(number);
        }
   } 

   return number;
}

See also

  • How to convert words to a number?

  • How to convert number to words in java

like image 108
flotothemoon Avatar answered May 11 '26 21:05

flotothemoon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!