简介:
我们经常会遇到需要将数值转换为单词的场景他们相应的单词表示。在 Java 中,没有直接执行此转换的内置函数。但是,通过一些自定义代码,我们可以开发一个满足我们要求的解决方案。
自定义解决方案:
我们可以创建一个自定义类来处理转换过程。让我们分解一下该方法:
此代码演示了自定义解决方案:
import java.text.DecimalFormat; public class EnglishNumberToWords { private static final String[] tensNames = { "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }; private static final String[] numNames = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; private EnglishNumberToWords() {} private static String convertLessThanOneThousand(int number) { // Handle numbers between 0 and 99 String soFar; if (number % 100 < 20){ soFar = numNames[number % 100]; number /= 100; } else { soFar = numNames[number % 10]; number /= 10; soFar = tensNames[number % 10] + soFar; number /= 10; } if (number == 0) return soFar; return numNames[number] + " hundred" + soFar; } public static String convert(long number) { if (number == 0) { return "zero"; } String snumber = Long.toString(number); String mask = "000000000000"; DecimalFormat df = new DecimalFormat(mask); snumber = df.format(number); // Handle billions, millions, hundred thousands, and thousands separately int billions = Integer.parseInt(snumber.substring(0,3)); int millions = Integer.parseInt(snumber.substring(3,6)); int hundredThousands = Integer.parseInt(snumber.substring(6,9)); int thousands = Integer.parseInt(snumber.substring(9,12)); String tradBillions; switch (billions) { case 0: tradBillions = ""; break; case 1 : tradBillions = convertLessThanOneThousand(billions) + " billion "; break; default : tradBillions = convertLessThanOneThousand(billions) + " billion "; } String result = tradBillions; String tradMillions; switch (millions) { case 0: tradMillions = ""; break; case 1 : tradMillions = convertLessThanOneThousand(millions) + " million "; break; default : tradMillions = convertLessThanOneThousand(millions) + " million "; } result = result + tradMillions; String tradHundredThousands; switch (hundredThousands) { case 0: tradHundredThousands = ""; break; case 1 : tradHundredThousands = "one thousand "; break; default : tradHundredThousands = convertLessThanOneThousand(hundredThousands) + " thousand "; } result = result + tradHundredThousands; String tradThousand; tradThousand = convertLessThanOneThousand(thousands); result = result + tradThousand; return result.replaceAll("^\s+", "").replaceAll("\b\s{2,}\b", " "); } }
System.out.println(EnglishNumberToWords.convert(123456789)); // Output: "one hundred twenty three million four hundred fifty six thousand seven hundred eighty nine"
使用此自定义解决方案,您可以将数值转换为轻松高效地表达他们的文字。
以上是如何在 Java 中将数字转换为单词?的详细内容。更多信息请关注PHP中文网其他相关文章!