Posted on 2008-07-10 19:43
笑看风云 阅读(255)
评论(1) 编辑 收藏 所属分类:
Java
最近在做开发的时候,有一部分功能要实现把数字转换成中文货币表示并显示给客户端,想了好久不知道如何写,到google上搜了一下,结果这方面的资料还比较多,看了一下别人写的,感觉很不错,就把它复制过来,根据实际需要改了一下,已经测试成功了.代码如下:
package test;
import java.math.BigDecimal;
public class StrangeCurrency {
/** *//**
* Description 将数字金额转换为中文金额
*
*/
public static String DoNumberCurrencyToChineseCurrency(
double bigdMoneyNumber) {
// 中文金额单位数组
String[] straChineseUnit = { "分", "角", "圆", "拾", "佰", "仟", "万", "拾",
"佰", "仟", "亿", "拾", "佰", "仟" };
// 中文数字字符数组
String[] straChineseNumber = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒",
"捌", "玖" };
String strChineseCurrency = "";
// 零数位标记
boolean bZero = true;
// 中文金额单位下标
int ChineseUnitIndex = 0;
// DoPrintMessage("Calling Method DoNumberCurrencyToChineseCurrency");
try {
if (bigdMoneyNumber == 0)
return "零圆整";
// 处理小数部分,四舍五入
double doubMoneyNumber = Math.round(bigdMoneyNumber * 100);
// 是否负数
boolean bNegative = doubMoneyNumber < 0;
// 取绝对值
doubMoneyNumber = Math.abs(doubMoneyNumber);
// 循环处理转换操作
while (doubMoneyNumber > 0) {
// 整的处理(无小数位)
if (ChineseUnitIndex == 2 && strChineseCurrency.length() == 0)
strChineseCurrency = strChineseCurrency + "整";
// 非零数位的处理
if (doubMoneyNumber % 10 > 0) {
strChineseCurrency = straChineseNumber[(int) doubMoneyNumber % 10]
+ straChineseUnit[ChineseUnitIndex]
+ strChineseCurrency;
bZero = false;
}
// 零数位的处理
else {
// 元的处理(个位)
if (ChineseUnitIndex == 2) {
// 段中有数字
if (doubMoneyNumber > 0) {
strChineseCurrency = straChineseUnit[ChineseUnitIndex]
+ strChineseCurrency;
bZero = true;
}
}
// 万、亿数位的处理
else if (ChineseUnitIndex == 6 || ChineseUnitIndex == 10) {
// 段中有数字
if (doubMoneyNumber % 1000 > 0)
strChineseCurrency = straChineseUnit[ChineseUnitIndex]
+ strChineseCurrency;
}
// 前一数位非零的处理
if (!bZero)
strChineseCurrency = straChineseNumber[0]
+ strChineseCurrency;
bZero = true;
}
doubMoneyNumber = Math.floor(doubMoneyNumber / 10);
ChineseUnitIndex++;
}
// 负数的处理
if (bNegative)
strChineseCurrency = "负" + strChineseCurrency;
} catch (Exception e) {
// DoPrintMessage("Exception Reason : Call Method
// DoNumberCurrencyToChineseCurrency Error");
// DoPrintMessage("Exception Message : " + e.getMessage());
e.printStackTrace();
return "";
}
return strChineseCurrency;
}
/**
* @param args
*/
//测试代码
public static void main(String[] args) {
double rmb=23434.89;
StrangeCurrency sc=new StrangeCurrency();
String s=sc.DoNumberCurrencyToChineseCurrency(rmb);
System.out.println(s);
}
}