题解 | #人民币转换#
人民币转换
https://www.nowcoder.com/practice/00ffd656b9604d1998e966d555005a4b
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextDouble()) {
System.out.println(f(in.nextDouble()));
}
}
public static String f(double d) {
String temp = d + "";
String content = "人民币";
double c = Double.parseDouble(temp.substring(0, temp.indexOf(".") + 1));
if (c < 10000 && c >= 1) {
content += e9999(c) + "元";
} else if (c > 10000){
content += getExtend(c) + "元";
}
double c2 = Double.parseDouble(temp.substring(temp.indexOf(".")));
content += el(c2);
return content;
}
public static String getExtend(double d) {
if (d < 10000) return "";
String[] dict = {"亿", "万"};
double base = 1 * 10000 * 10000d;
String content = "";
int hindx = 0;
while (hindx < 2) {
double n = (int) (d / base);
double c = n % base;
if (c != 0) {
if (hindx == 1) {
double save = d % base;
if (save == 0) {
content += e9999(c) + dict[hindx];
} else {
if (save < 1000) {
content += e9999(c) + dict[hindx] + "零" + e999(save);
} else {
content += e9999(c) + dict[hindx] + e9999(save);
}
}
} else {
content += e9999(c) + dict[hindx];
}
}
d %= base;
base /= 10000;
hindx++;
}
return content;
}
public static String e9999(double d) {
if (d < 0 || d > 9999) return "";
if (d <= 10) {
return e9(d);
}
if (d > 10 && d < 100) {
return e99(d);
}
if (d > 99 && d < 1000) {
return e999(d);
}
double h = (int) (d / 1000);
double m1 = (int) (d % 1000 / 100);
double m2 = d % 100 / 10;
double l = d % 10;
if (m1 == 0) {
return e9(h) + "仟零" + e99(d - h * 1000);
} else {
return e9(h) + "仟" + e999(d - h * 1000);
}
}
public static String e999(double d) {
if (d < 0 || d > 999) return "";
if (d <= 10) {
return e9(d);
}
if (d > 10 && d < 100) {
return e99(d);
}
double h = (int) (d / 100);
double m = (int) ((int) (d % 100) / 10);
double l = d % 10;
if (m == 0) {
return e9(h) + "佰零" + e9(l);
} else if (m == 1) {
return e9(h) + "佰拾" + e9(l);
} else {
return e9(h) + "佰" + e9(m) + "拾" + e9(l);
}
}
public static String e99(double d) {
if (d < 0 || d > 99) {
return "";
}
if (d > 0 && d <= 10) {
return e9(d);
}
double c = (int) (d / 10);
if (c == 1) {
return "拾" + e9(d % 10);
} else {
return e9(c) + "拾" + e9(d % 10);
}
}
public static String e9(double d) {
if (d <= 0 || d > 10) return "";
String[] names = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖", "拾"};
return names[(int) d];
}
public static String el(double d) {
int a = (d + "").charAt(2) -'0';
int b = 0;
if ((d + "").length() == 4) {
b = (d + "").charAt(3) -'0';
}
double one = a, two = b;
if (one > 0 && two > 0) {
return e9(one) + "角" + e9(two) + "分";
} else if (one > 0 && two == 0) {
return e9(one) + "角";
} else if (one == 0 && two > 0) {
return e9(two) + "分";
} else {
return "整";
}
}
}
查看13道真题和解析