首页 » 技术分享 » 阿拉伯数字转中文数字

阿拉伯数字转中文数字

 

package algorithm.other;

/**
* 阿拉伯数字转中文数字
* @author CEMABENTENG
*
*/
public class ChineseNum
{
private static String[] chnNumChar =
{ "零", "一", "二", "三", "四", "五", "六", "七", "八", "九" };

private static String[] chnUnitSection =
{ "", "万", "亿", "万" };

private static String[] chnUnitChar =
{ "", "十", "百", "千" };

public static void main(String[] args)
{
System.out.println(numToChn(0));
System.out.println(numToChn(1000021000));
System.out.println(numToChn(10));
System.out.println(numToChn(11));
System.out.println(numToChn(100));
System.out.println(numToChn(101));
System.out.println(numToChn(203));
System.out.println(numToChn(1001));
System.out.println(numToChn(1210121003));
for (int i = 0; i < 10; i++)
{
long a = (long) Math.floor(Math.random() * 999900000000l);
System.out.println(a + "~~~~~~~" + numToChn(a));
}
}

/**
* 阿拉伯数字转中文数字
* @param num 一万亿以内正整数
* @return
*/
public static String numToChn(long num)
{
String chnStr = "";
String strIns = "";
int unitPos = 0;
boolean zero = false;
while (num > 0)
{
int section = (int) (num % 10000);
if (zero)
{
chnStr = chnNumChar[0] + chnStr;
}
strIns = SectionToChn(section);

strIns += (section != 0) ? chnUnitSection[unitPos] : chnUnitSection[0];
chnStr = strIns + chnStr;
zero = (section < 1000) && (section > 0);
num = num / 10000;
unitPos++;
}

if (chnStr.length() == 0)
{
return chnNumChar[0];
}

return chnStr;
}

private static String SectionToChn(int section)
{
String x = "";
String strIns;
int unitPos = 0;//位数
boolean zero = true;
while (section > 0)
{
int v = section % 10;
if (v == 0)
{
if ((section == 0) || !zero)
{
zero = true;
x = chnNumChar[v] + x;//补零
}
} else
{
zero = false;
strIns = chnNumChar[v];
strIns += chnUnitChar[unitPos];
//去一
if (section < 10 && strIns.equals(chnNumChar[1] + chnUnitChar[1]))
{
strIns = strIns.substring(1);
}
x = strIns + x;
}
unitPos++;
section = section / 10;
}
return x;
}
}

转载自原文链接, 如需删除请联系管理员。

原文链接:阿拉伯数字转中文数字,转载请注明来源!

0