黑马程序员技术交流社区
标题:
面试题数字转金额求解带角分的?
[打印本页]
作者:
敲敲敲dm
时间:
2016-9-4 22:26
标题:
面试题数字转金额求解带角分的?
本帖最后由 敲敲敲dm 于 2017-2-6 22:42 编辑
F:\黑马资料\day04\myday04\new对象的内存图\New 对象时的内存图.png
作者:
敲敲敲dm
时间:
2017-2-10 17:07
//想了好几天写出来的大家看看有没有bug
public class NumberToMoney {
public static final String[] utils = { "分", "角", "元", "拾", "佰", "仟", "万",
"拾", "佰", "仟", "亿", "拾", "佰", "仟", "万" };
public static final String[] number = { "零", "壹", "贰", "叁", "肆", "伍", "陆",
"柒", "捌", "玖" };
public static void main(String[] args) {
numToMoney();
}
public static void numToMoney() {
while (true) {
System.out.println("请输入数字:");
Scanner sc = new Scanner(System.in);
double d = 0;
try {
d = sc.nextDouble();
} catch (Exception e) {
// TODO: handle exception
System.out.println("您输入的的输入格式不对");
return;
}
BigDecimal b = new BigDecimal(d);
BigDecimal b2 = b.setScale(2, BigDecimal.ROUND_HALF_EVEN);
BigDecimal b3 = new BigDecimal(100).multiply(b2);
// int x=b3.intValue();
long x = b3.longValue();
trans(x);
}
}
public static void trans(long x) {
StringBuilder sb = null;
try {
sb = new StringBuilder();
int index = 0;
while (x != 0) {
// sb.insert(0, utils[index]);
sb.insert(0, number[(int) (x % 10)] + utils[index]);
x = x / 10;
index++;
}
} catch (Exception e) {
// TODO: handle exception
System.out.println("格式不对");
return;
}
String str = sb.toString();
String money = str.replaceAll("零[仟佰拾]", "零").replaceAll("零+万", "万")
.replaceAll("零+亿", "亿").replaceAll("亿万", "亿零")
.replaceAll("零+", "零").replaceAll("零元", "元")
.replaceAll("零角", "").replaceAll("零分", "");
if (money.startsWith("壹拾")) {
String money1 = money.substring(1);
System.out.println(money1);
} else {
System.out.println(money);
}
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2