-3

Currently I'm attempting to convert a number to a word, but I'm unable to get the result that I want. Basically, my question is if I can convert a double to a string, the number converted into words, one for each decimal number, including the decimal points.

This is my method

String numberInWords (double numbers){
    String result = "" + numbers;
    for (int i = 0; i < result.length(); i++) {
        if( i == 0) {
            result += "zero";
        }
        if(i == 1) {
            result += "one";
        }
        if(i == 2) {
            result += "two";
        }
        if(i == 3) {
            result += "three";
        }
        if(i == 4) {
            result += "four";
        }
        if(i == 5) {
            result += "five";
        }
        if(i == 6) {
            result += "six";
        }
        if(i == 7) {
            result += "seven";
        }
        if(i == 8) {
            result += "eight";
        }
        if(i == 9) {
            result += "nine";
        }
    }
   return result;

}

and the result :

Expected :two three
Actual   :23.0zeroonetwothreefourfivesixseveneightnine
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • First, you shouldn't use `String result = "" + numbers;`, Second, You compare the `i` and not the digits in the number. – Youcef LAIDANI Oct 14 '20 at 08:19
  • 4
    Does this answer your question? [How to convert number to words in java](https://stackoverflow.com/questions/3911966/how-to-convert-number-to-words-in-java) – Iurii Drozdov Oct 14 '20 at 08:19
  • you may also follow this: https://www.geeksforgeeks.org/convert-number-to-words/ – Sakib Ahammed Oct 14 '20 at 08:20
  • I don't think the dupe is what OP wants. The dupe is covering the whole number as one and not the digits separately (like asked here). – dly Oct 14 '20 at 08:22
  • Hint: [`charAt()`](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html) should do in your case. – dly Oct 14 '20 at 08:28
  • The `result` you return shouldn't start with `23.0`, so don't use the same variable to iterate over and to return. And `i` isn't the digit it's only its index in the string, you'll need to use charAt to retrieve the digit. Plus you'll need to handle that `.0` (do you really want your input to be a `double` ? might be easier if you start with an `int`) – Aaron Oct 14 '20 at 08:29
  • 1
    Many things wrong with your code. It is for example a really bad approach to iterate over a string, while **changing** it over and over again. You should **first** step back and ask yourself: how do I get to the digits in my number (or the chars of the number as string)? How do I get from a digit like 1 to a string "one", and so on. – GhostCat Oct 14 '20 at 08:31

2 Answers2

1

There are much more elegant ways to have this done, but I did it in a way that affects your code the least.

So, if you really want to have a double as an input, you will also want to enable to have 23L being printed as "two three point zero" because it is 23.0, if not, you can tweak my snippet, but that is what it will provide for you.

    String numberInWords (double numbers){
        char[] numberInCharacters = String.valueOf(numbers).toCharArray();

        String result = "";
        for (int i = 0; i < numberInCharacters.length; i++) {
            if(i != 0) {
                result += " ";
            }

            if( numberInCharacters[i] == '0') {
                result += "zero";
            }
            else if(numberInCharacters[i] == '1') {
                result += "one";
            }
            else if(numberInCharacters[i] == '2') {
                result += "two";
            }
            else if(numberInCharacters[i] == '3') {
                result += "three";
            }
            else if(numberInCharacters[i] == '4') {
                result += "four";
            }
            else if(numberInCharacters[i] == '5') {
                result += "five";
            }
            else if(numberInCharacters[i] == '6') {
                result += "six";
            }
            else if(numberInCharacters[i] == '7') {
                result += "seven";
            }
            else if(numberInCharacters[i] == '8') {
                result += "eight";
            }
            else if(numberInCharacters[i] == '9') {
                result += "nine";
            }
            else if (numberInCharacters[i] == '.') {
                result += "point";
            }
        }

        return result;
    }

If you only want predecimal part then you can transform the double to int and lose the decimal part then continue with the process to stringify it.

kiselitza
  • 119
  • 8
  • What happens to the last space? Why not iterate through the char[] directly, instead of accessing it 10 times each iteration of the loop? Why continue to use String concatenation (in a loop nonetheless) instead of a StringBuilder? Why execute every `if statement` every time? If you have a 100 digit number, you would check 1100 `if statements`, is that ok? – AlexT Oct 14 '20 at 08:47
  • 1
    Like i mentioned, there are MUCH more elegant solutions, I noticed that this is the only interaction of this contributor in stackoverflow meaning he/she is probably a novice. As much as you are fully correct with suggestions, my goal was to actually make as little as possible of changes in order to provide the asked outcome. – kiselitza Oct 14 '20 at 08:49
  • I would disagree, novices should be told the best practices from the start, what is the point in learning a language if you start by learning it wrong? When they will eventually need to write proper code they will have a foundation of random mistakes that will add up. I also strongly disagree that your code provides the asked outcome, due to the trailing whitespace, which is a bug waiting to bite somebody (not in this code, especially if it just prints to the console, but in general) – AlexT Oct 14 '20 at 08:55
0

Although the code provided by kiselica-aldin will work ok, it doesn't solve most of the issues. It will also add a bug, since the last whitespace is never removed.

I've left comments to explain parts of the code.

public String numberInWords (double numbers){
        String numbersAsString = String.valueOf(numbers); // "" + numbers isn't the best way of doing it
        StringBuilder result = new StringBuilder(); //string builder is better that string concatenation
        //we can iterate through the char list directly, no need to iterate through numbers and then access the char[] every time
        for (char digit : numbersAsString.toCharArray()) {
            if( digit == '0') {
                result.append("zero "); //adding a trailing space, since you want them separated
                continue; //what is the point of doing the other if statements if we already have a result?
            }
            if( digit == '1') {
                result.append("one ");
                continue;
            }
            if( digit == '2') {
                result.append("two ");
                continue;
            }
            if( digit == '3') {
                result.append("three ");
                continue;
            }
            if( digit == '4') {
                result.append("four ");
                continue;
            }
            if( digit == '5') {
                result.append("five ");
                continue;
            }
            if( digit == '6') {
                result.append("six ");
                continue;
            }
            if( digit == '7') {
                result.append("seven ");
                continue;
            }
            if( digit == '8') {
                result.append("eight ");
                continue;
            }
            if( digit == '9') {
                result.append("nine ");
                continue;
            }
            if( digit == '.') {
                result.append("dot "); //or comma, or whatever, since there is a big difference between 1.25 and 125
                //nothing to continue since it already is the last one
            }
        }
        return result.toString().trim(); //trim to remove the last space
    }
AlexT
  • 2,524
  • 1
  • 11
  • 23
  • I have found a solution towards it by using formatting data, i appreciate the help as the answer you guys gave me also give me some ideas how to do the final code! – SliverSaint Fox Oct 14 '20 at 14:46