Here you can find the source of numToWords(long num)
Parameter | Description |
---|---|
num | Number to get the word for |
public static String numToWords(long num)
//package com.java2s; //License from project: Open Source License public class Main { /**//from www.j a va 2s .c o m * Gets a word from a number in between 1-999 * @param num * Number to get the word for * @return * The number in words with British usage */ public static String numToWords(long num) { String[] ones = new String[] { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; int[] onesLen = new int[] { 3, 3, 5, 4, 5, 3, 5, 5, 4 }; String[] teens = new String[] { "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; int[] teensLen = new int[] { 6, 6, 8, 8, 7, 7, 9, 8, 8 }; String[] tens = new String[] { "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }; int[] tensLen = new int[] { 3, 5, 6, 5, 5, 5, 7, 6, 6 }; String numStr = String.valueOf(num); StringBuilder result = new StringBuilder(); int one = Integer.valueOf(String.valueOf(numStr.charAt(numStr .length() - 1))); result.insert(0, one > 0 ? ones[one - 1] + " " : ""); if (num >= 10) { int ten = Integer.valueOf(String.valueOf(numStr.charAt(numStr .length() - 2))); if (ten > 1) { result.insert(0, tens[ten - 1] + " "); } else if (ten == 0) { } else { result = new StringBuilder(one > 0 ? teens[one - 1] : "ten"); } } if (num >= 100) { int hundred = Integer.valueOf(String.valueOf(numStr .charAt(numStr.length() - 3))); int ten = Integer.valueOf(String.valueOf(numStr.charAt(numStr .length() - 2))); result.insert(0, ones[hundred - 1] + (one == 0 && ten == 0 ? " hundred " : " hundred and ")); } return result.toString(); } }