java 数字转大写_java 数字转大写 100行内搞定

import java.math.BigDecimal;

/**

*

*@author jack chen

*@since 2009-07

*/

public class Number2char{

/*

eg:640 409 329

987 654 321 //对应的坐标

&&& &&& &&& //替换成对应的字符 (如果是0加上标记)

--- --- --- //每位修辞符常量

* //每隔5位数字修辞符常量

*/

//数字转中文常量

private final static String[] C_N = {"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};

//每隔5位数字修辞符常量

private final static String[] C_F = {"","万","亿","兆","吉","太","拍","艾"};

//对应的每位修辞符常量

private final static String[] C_S = {"","拾","佰","仟"};

private final static String[] CNY = {"元", "角", "分", "毫", "厘"};

//"-"

private final static String negative = "负";

//"+"

private final static String positive = "";

/**将整数转换成对应的中文字符串

*@param l

*@return StringBuffed

*/

public static String toChineseChar(long l){

//定义变量保存中文字符串

StringBuilder sb = new StringBuilder();

//将阿拉伯数字转换为无符号的字符串数组

char [] ch = (Math.abs(l)+"").toCharArray();

//加上符号

sb.append(l<0?negative:positive);

//定义一个标记,判断该数位前面是否有'0'

boolean beforeHaveZore = false;

//遍历中文字符串

for(int i = 0,j = ch.length-1;i

//如果首位是1且是十位就不用加'壹'了:eg 15 拾伍 150213 拾伍万零贰佰壹叁 150013 拾伍万零壹拾叁 拾亿零壹拾万/拾亿零拾万

if(i == 0 && ch[i]-48 == 1 && j%4 == 1){

sb.append(C_S[1]);

//判断这个数字是否为0且它前面没有0

}else if(ch[i] !=48 && !beforeHaveZore)

//中文常量 + 对应的每位修辞符常量 + 每隔4位数字修辞符常量

sb.append(C_N[ch[i]-48]+C_S[j%4] + C_F[j%4 == 0?j/4:0]);

//判断这个数字是否为0且它前面有0

else if(ch[i] !=48 && beforeHaveZore){

//中文常量"零"+中文常量+对应的每位修辞符常量+每隔4位数字修辞符常量

sb.append(C_N[0]+C_N[ch[i]-48]+C_S[j%4] + C_F[j%4 == 0?j/4:0]);

//消出标记

beforeHaveZore = false;

//这个数字是0

}else{

//如果这个数的位置不是第5位?标记:不标记

beforeHaveZore = beforeHaveZore||j%4!=0;

//每隔5位数字修辞符常量 eg: 50000 伍万

sb.append( C_F[j%4 == 0?j/4:0]);

}

}

return sb.toString();

}

/**

* To CNY

* @param d

* @return

*/

public static String toChineseCNY(Double d) {

long l = d.longValue();

if (d - l == 0) {

return toChineseChar(l) + CNY[0] + "整";

}

String s = (d + "").split("\\.")[1];

StringBuffer sb = new StringBuffer(s.length() * 2);

int i = 1;

for (char c : s.toCharArray()) {

if (c-48 == 0) {

i ++;

continue;

}

sb.append(C_N[c-48] + CNY[i ++]);

if (CNY.length == i) {

break;

}

}

return toChineseChar(l) + CNY[0]+ sb;

}

public static String toChineseChar (Double d) {

long l = d.longValue();

if (d - l == 0) {

return toChineseChar(l);

}

String s = (BigDecimal.valueOf(d).toPlainString()).split("\\.")[1];

StringBuffer sb = new StringBuffer(s.length());

sb.append("点");

for (char c : s.toCharArray()) {

sb.append(C_N[c-48]);

}

return toChineseChar(l) + sb;

}

public static void main(String[] args) {

System.out.println(toChineseChar(120_030));//拾贰万零叁拾

System.out.println(toChineseChar(120_003));//拾贰万零叁

System.out.println(toChineseChar(12_000_003));//壹仟贰佰万零叁

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值