使用java代码实现将整数转化成英语语法,百位数和十位数之间要加上and,百分位为零的话,省略and
时间: 2023-05-21 19:00:39 浏览: 105
Java实现数字转成英文的方法
Sure, here's a Java code snippet that can convert an integer to its English language equivalent:
```
public static String intToEnglish(int num) {
if (num == 0) {
return "zero";
}
String[] ones = {"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
String[] tens = {"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
String[] thousands = {"", "thousand", "million", "billion"};
int i = 0;
String words = "";
while (num > 0) {
if (num % 1000 != 0) {
String word = "";
int n = num % 100;
if (n < 20) {
word = ones[n];
} else {
word = tens[n / 10] + (n % 10 != 0 ? " " + ones[n % 10] : "");
}
if (num % 100 < 20 && num % 100 != 0) {
words = word + " " + thousands[i] + " and " + words;
} else {
words = word + " " + thousands[i] + " " + words;
}
}
num /= 1000;
i++;
}
return words.trim();
}
```
You can call this method with an integer as an argument, and it will return the English language equivalent of that number. For example, `intToEnglish(123)` would return `"one hundred and twenty three"`.
阅读全文