java 将数字转换成英文
时间: 2023-10-11 21:13:22 浏览: 75
可以使用以下代码将数字转换成英文:
```
public class NumberToWords {
private static final String[] tensNames = {
"",
" ten",
" twenty",
" thirty",
" forty",
" fifty",
" sixty",
" seventy",
" eighty",
" ninety"
};
private static final String[] numNames = {
"",
" one",
" two",
" three",
" four",
" five",
" six",
" seven",
" eight",
" nine",
" ten",
" eleven",
" twelve",
" thirteen",
" fourteen",
" fifteen",
" sixteen",
" seventeen",
" eighteen",
" nineteen"
};
private NumberToWords() {}
private static String convertLessThanOneThousand(int number) {
String current;
if (number % 100 < 20) {
current = numNames[number % 100];
number /= 100;
} else {
current = numNames[number % 10];
number /= 10;
current = tensNames[number % 10] + current;
number /= 10;
}
if (number == 0) return current;
return numNames[number] + " hundred" + current;
}
public static String convert(int number) {
if (number == 0) {
return "zero";
}
String prefix = "";
if (number < 0) {
number = -number;
prefix = "negative";
}
String current = "";
int place = 0;
do {
int n = number % 1000;
if (n != 0){
String s = convertLessThanOneThousand(n);
current = s + place + current;
}
place++;
number /= 1000;
} while (number > 0);
return (prefix + current).trim();
}
}
```
使用示例:
```
System.out.println(NumberToWords.convert(123456789));
```
输出结果:
```
one hundred twenty three million four hundred fifty six thousand seven hundred eighty nine
```
相关推荐
![text/x-c++](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)