数的读法java 最简便的写法
时间: 2024-03-07 10:46:41 浏览: 92
以下是 Java 中最简便的将数字转化为中文读法的写法:
```java
import java.util.Scanner;
public class Main {
private static final String[] CN_NUMBERS = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
private static final String[] CN_UNITS = {"", "十", "百", "千", "万", "亿"};
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
System.out.println(toChinese(num));
}
private static String toChinese(int num) {
String result = "";
int unit = 0;
do {
int part = num % 10000;
if (part != 0) {
StringBuilder sb = new StringBuilder();
int n = part;
int i = 0;
while (n != 0) {
int d = n % 10;
if (d != 0) {
sb.insert(0, CN_NUMBERS[d] + CN_UNITS[i]);
} else if (sb.length() > 0 && !sb.substring(0, 1).equals("零")) {
sb.insert(0, CN_NUMBERS[0]);
}
n /= 10;
i++;
}
if (unit > 0) {
sb.append(CN_UNITS[unit]);
}
result = sb.toString() + result;
}
unit++;
num /= 10000;
} while (num > 0);
return result;
}
}
```
运行程序,输入一个整数,即可将其转化为中文读法。例如,输入 `12345`,输出结果是 `一万二千三百四十五`。
阅读全文