1

Need a modify the program to convert decimal values to words.

Success

Example 1: Enter the amount : 20

answer: Twenty Rupees Only.

Error:

Example 2: Enter the amount : 20.50

answer: Twenty Rupees and Fifty Paisa.

Actually i can convert number to words.

i couldn't able to convert decimal values as above.

Thanks in Advance.

import java.text.NumberFormat;
import java.util.Scanner;

public class NumberToWordsConverter {

public static final String[] units = { "", "One", "Two", "Three", "Four",
"Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve",
"Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen",
"Eighteen", "Nineteen" };

public static final String[] tens = { 
        "",         // 0
        "",     // 1
        "Twenty",   // 2
        "Thirty",   // 3
        "Forty",    // 4
        "Fifty",    // 5
        "Sixty",    // 6
        "Seventy",  // 7
        "Eighty",   // 8
        "Ninety"    // 9
};

public static String convert(final int n) {
    if (n < 0) {
        return "Minus " + convert(-n);
    }

    if (n < 20) {
        return units[n];
    }

    if (n < 100) {
        return tens[n / 10] + ((n % 10 != 0) ? " " : "") + units[n % 10];
    }

    if (n < 1000) {
        return units[n / 100] + " Hundred" + ((n % 100 != 0) ? " " : "") + convert(n % 100);
    }

    if (n < 100000) {
        return convert(n / 1000) + " Thousand" + ((n % 10000 != 0) ? " " : "") + convert(n % 1000);
    }

    if (n < 10000000) {
        return convert(n / 100000) + " Lakh" + ((n % 100000 != 0) ? " " : "") + convert(n % 100000);
    }

    return convert(n / 10000000) + " Crore" + ((n % 10000000 != 0) ? " " : "") + convert(n % 10000000);
}

public static void main(final String[] args) {

    int n;
    Scanner s=new Scanner(System.in);
    System.out.println("Enter a number to convert into word format");
    n =s.nextInt();
    System.out.println(NumberFormat.getInstance().format(n) + "='" + convert(n) + "'");

}
}
Praveen
  • 43
  • 2
  • 8

2 Answers2

0

Try http://www.rgagnon.com/javadetails/java-0426.html

Just change the code so "Rupees" appears after each whole number and "Paisa" after each decimal value.

You will probably want to edit the code a bit, so it works

ayunami2000
  • 441
  • 6
  • 10
0

Change your int to a String. To get the different units you can use String#splt, in this case you want to split '.' so e.g.

String value = Scanner.next();
String[] values = value.split(".");

Now values[0] is 20 and values[1] is 50

If you need any further help with your problem let me know but I think this is enough to lead you to the right direction!

Dinh
  • 759
  • 5
  • 16