题目
编写一段程序,实现从控制台中读取一个数字,然后打印出这个数字四舍五入后对应的人民币大写汉字字符。例如:
输入:3000
输出:叁仟元
输入:300.569
输出:叁佰元伍角柒分
思路
使用数组保存人民币大写汉字和单位,通过循环取得数字的每一位数字,然后转换成汉字,最后组合输出。此代码中支持最大数为仟亿(可在代码中修改增加位数)。
代码
package p1;
import java.util.Scanner;
public class Demo0903 {
public static void main(String[] args) {
double n = 300.569;
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
n = scanner.nextDouble();
n = Math.round(n * 100) / 100.0;
System.out.println(superCase(n));
}
scanner.close();
}
// 壹、贰、叁、肆、伍、陆、柒、捌、玖、拾、佰、仟、万、 亿、元、角、分、零、整(正)
public static String superCase(double n) {
StringBuilder sb = new StringBuilder();
long num = ((long) (n * 100));
// System.out.println(num);
int a = 0;
// System.out.println(num);
for (int i = 14; i > 0; i--) {
// System.out.println(num / Math.pow(10, (10 - i)) % 10);
a = (int) (num / Math.pow(10, (i - 1)) % 10);
// System.out.println(a);
if (a != 0) {
sb.append(num2Char(a));
sb.append(unit(i));
} else if (i == 3 && n >= 1) {
sb.append(unit(i));
}
}
return sb.toString();
}
public static String num2Char(int num) {
String[] strings = { "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖", "拾" };
if (num <= strings.length && num >= 1) {
return strings[num - 1];
} else {
return String.valueOf(num);
}
}
public static String unit(int n) {
String[] strings = { "分", "角", "元", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟" };
if (n <= strings.length && n >= 1) {
return strings[n - 1];
} else {
return "";
}
}
}