请用Java实现人民币大写转换小写

2015-01-06 06:30:01 阅读( 92 )

2534人 收藏本页

标签:Java面试题

/**
* 人民币大写转换小写
*
* @param money
*/
public static long convertUpperToNum(String money) {
long result = 0l;
/**
* 先分割出各级别(亿、万、个)
*/
String yi = money.indexOf(“亿”) != -1 ? money.substring(0, money
.indexOf(“亿”) + 1) : “”; // 亿
if (!”".equals(yi)) {
result = convertUpperToNum(yi.substring(0, yi.length() – 1)) * 100000000; // 计算亿前面的值
}
money = money.indexOf(“亿”) != -1 ? money
.substring(money.indexOf(“亿”) + 1) : money;
String wan = money.indexOf(“万”) != -1 ? money.substring(0, money
.indexOf(“万”) + 1) : “”; // 万
money = money.indexOf(“万”) != -1 ? money
.substring(money.indexOf(“万”) + 1) : money; // 个
// System.out.println(“亿:” + yi + ” 万:” + wan + ” 个:” + money);
long wanNum = !”".equals(wan) ? calcNum(wan, 2) : 0;
long geNum = !”".equals(money) ? calcNum(money, 1) : 0;
result = result + wanNum + geNum;
// System.out.println(result);
return result;
}
/**
* 计算各级别的数值
*
* @param money
* @return
*/
public static long calcNum(String money, int index) {
long num = 0l;
if (index != 1) {
// System.out.println(“money:” + money);
money = money.substring(0, money.length() – 1);
}
/**
* 分割千、百、十、个
*/
String qian = money.indexOf(“仟”) != -1 ? money.substring(0, money
.indexOf(“仟”)) : “”; // 仟
if (!”".equals(qian)) {
num += upperToNum(qian.charAt(qian.length() – 1)) * 1000;
}
money = money.indexOf(“仟”) != -1 ? money
.substring(money.indexOf(“仟”) + 1) : money;
String bai = money.indexOf(“佰”) != -1 ? money.substring(0, money
.indexOf(“佰”)) : “”; // 佰
if (!”".equals(bai)) {
num += upperToNum(bai.charAt(bai.length() – 1)) * 100;
}
money = money.indexOf(“佰”) != -1 ? money
.substring(money.indexOf(“佰”) + 1) : money;
String shi = money.indexOf(“拾”) != -1 ? money.substring(0, money
.indexOf(“拾”)) : “”; // 拾
if (!”".equals(shi)) {
num += upperToNum(shi.charAt(shi.length() – 1)) * 10;
}
// System.out.println(“个位:” + money);
if (!”".equals(money)) {
money = money.indexOf(“拾”) != -1 ? money.substring(money
.indexOf(“拾”) + 1) : money.substring(money.length() – 1); // 个
if (!”".equals(money)) {
num += upperToNum(money.charAt(money.length() – 1));
}
}
switch (index) {
case 1: // 个
break;
case 2: // 万
num = num * 10000;
break;
}
return num;
}
/**
* 小写转大写
*
* @param value
* @return
*/
public static int upperToNum(char value) {
int num = 0;
switch (value) {
case ‘零’:
break;
case ‘壹’:
num = 1;
break;
case ‘贰’:
num = 2;
break;
case ‘叁’:
num = 3;
break;
case ‘肆’:
num = 4;
break;
case ‘伍’:
num = 5;
break;
case ‘陆’:
num = 6;
break;
case ‘柒’:
num = 7;
break;
case ‘捌’:
num = 8;
break;
case ‘玖’:
num = 9;
break;
}
return num;
}

来自IT公司面试手册

下一篇:Java线程:并发协作-生产者消费者模型

上一篇:java中日期和时间的处理

亲~ 如果您有更好的答案 可在评论区发表您独到的见解。

您想查看更多的信息: 面试题