阿拉伯数字的金额转换成中国传统的形式_java算法

合集下载

教你怎么用Java完成人民币大写转化

教你怎么用Java完成人民币大写转化

教你怎么⽤Java完成⼈民币⼤写转化⽬录⼀、前⾔⼆、注意三、思路分析四、完整代码五、代码测试⼀、前⾔⼈民币⼤写⾦额的正确写法:整数部分:零、壹、贰、叁、肆、伍、陆、柒、捌、玖⼩数部分:⾓、分、厘数位部分:拾、佰、仟、万、亿、元⼆、注意阿拉伯数字⼩写⾦额数字中有 “0” 时,中⽂⼤写应按照汉语语⾔规律、⾦额数字构成和防⽌涂改的要求进⾏书写。

举例如下:1、阿拉伯数字中间有 “0” 时,中⽂⼤写要写“零”字,如¥1409.50应写成⼈民币壹仟肆佰零玖元伍⾓。

2、阿拉伯数字中间连续有⼏个 “0” 时、中⽂⼤写⾦额中间可以只写⼀个“零”字,如¥6007.14应写成⼈民币陆仟零柒元壹⾓肆分。

3、阿拉伯⾦额数字万位和元位是 “0” ,或者数字中间连续有⼏个 “0” ,万位、元位也是 “0” 但千位、⾓位不是 “0” 时,中⽂⼤写⾦额中可以只写⼀个零字,也可以不写“零”字,如¥1680.32应写成⼈民币壹仟陆佰捌拾元零叁⾓贰分,或者写成⼈民币壹仟陆佰捌拾元叁⾓贰分。

⼜如¥107000.53应写成⼈民币壹拾万柒仟元零伍⾓叁分,或者写成⼈民币壹拾万零柒仟元伍⾓叁分。

4、阿拉伯⾦额数字⾓位是 “0” ⽽分位不是 “0” 时,中⽂⼤写⾦额“元”后⾯应写“零”字,如¥16409.02应写成⼈民币壹万陆仟肆佰零玖元零贰分,⼜如¥325.04应写成⼈民币叁佰贰拾伍元零肆分。

三、思路分析初始化⼈民币⼤写⾦额,其中数位的顺序是有要求的。

对传⼊的字符串进⾏校验(⾮空、特殊字符)判断字符串的长度是否超过了转换范围判断是否存在负数,对负号进⾏替换分离整数部分和⼩数部分判断整数部分是否已经达到万这⾥使⽤到了⼀个StringUtils类和单元测,junit,需要导⼊依赖<dependency><groupId>commons-lang</groupId><artifactId>commons-lang</artifactId><version>2.6</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency></dependencies>四、完整代码public class ConvertUpMoney {//整数部分的⼈民币⼤写private static final String[] NUMBERS = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};//数位部分private static final String[] IUNIT = {"元", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟", "万", "拾", "佰", "仟"};//⼩数部分的⼈民币⼤写private static final String[] DUNIT = {"⾓", "分", "厘"};//转成中⽂的⼤写⾦额public static String toChinese(String str) {//判断输⼊的⾦额字符串是否符合要求if (StringUtils.isBlank(str) || !str.matches("(-)?[\\d]*(.)?[\\d]*")) {System.out.println("抱歉,请输⼊数字!");return str;}//判断输⼊的⾦额字符串if ("0".equals(str) || "0.00".equals(str) || "0.0".equals(str)) {return "零元";}//判断是否存在负号"-"boolean flag = false;if (str.startsWith("-")) {flag = true;str = str.replaceAll("-", "");}//如果输⼊字符串中包含逗号,替换为 "."str = str.replaceAll(",", ".");String integerStr;//整数部分数字String decimalStr;//⼩数部分数字//分离整数部分和⼩数部分if (str.indexOf(".") > 0) {//整数部分和⼩数部分integerStr = str.substring(0, str.indexOf("."));decimalStr = str.substring(str.indexOf(".") + 1);} else if (str.indexOf(".") == 0) {//只存在⼩数部分 .34integerStr = "";decimalStr = str.substring(1);} else { //只存在整数部分 34integerStr = str;decimalStr = "";}//整数部分超出计算能⼒,直接返回if (integerStr.length() > IUNIT.length) {System.out.println(str + ":超出计算能⼒");return str;}//整数部分存⼊数组⽬的是为了可以动态的在字符串数组中取对应的值int[] integers = toIntArray(integerStr);//判断整数部分是否存在输⼊012的情况if (integers.length > 1 && integers[0] == 0) {System.out.println("抱歉,请输⼊数字!");if (flag) {str = "-" + str;}return str;}boolean isWan = isWanUnits(integerStr);//设置万单位//⼩数部分数字存⼊数组int[] decimals = toIntArray(decimalStr);String result = getChineseInteger(integers, isWan) + getChineseDecimal(decimals);//返回最终的⼤写⾦额 if (flag) {return "负" + result;//如果是负数,加上"负"} else {return result;}}//将字符串转为int数组private static int[] toIntArray(String number) {//初始化⼀维数组长度int[] array = new int[number.length()];//循环遍历赋值for (int i = 0; i < number.length(); i++) {array[i] = Integer.parseInt(number.substring(i, i + 1));}return array;}//将整数部分转为⼤写的⾦额public static String getChineseInteger(int[] integers, boolean isWan) {StringBuffer chineseInteger = new StringBuffer("");int length = integers.length;// 对于输⼊的字符串为 "0." 存⼊数组后为 0if (length == 1 && integers[0] == 0) {return "";}for (int i = 0; i < length; i++) {String key = "";//0325464646464if (integers[i] == 0) {if ((length - i) == 13)//万(亿)key = IUNIT[4];else if ((length - i) == 9) {//亿key = IUNIT[8];} else if ((length - i) == 5 && isWan) {//万key = IUNIT[4];} else if ((length - i) == 1) {//元key = IUNIT[0];}if ((length - i) > 1 && integers[i + 1] != 0) {key += NUMBERS[0];}}chineseInteger.append(integers[i] == 0 ? key : (NUMBERS[integers[i]] + IUNIT[length - i - 1]));}return chineseInteger.toString();}//将⼩数部分转为⼤写的⾦额private static String getChineseDecimal(int[] decimals) { //⾓分厘 038 壹分捌厘StringBuffer chineseDecimal = new StringBuffer("");for (int i = 0; i < decimals.length; i++) {if (i == 3) {break;}chineseDecimal.append(decimals[i] == 0 ? "" : (NUMBERS[decimals[i]] + DUNIT[i]));}return chineseDecimal.toString();}//判断当前整数部分是否已经是达到【万】private static boolean isWanUnits(String integerStr) {int length = integerStr.length();if (length > 4) {String subInteger = "";if (length > 8) {subInteger = integerStr.substring(length - 8, length - 4);} else {subInteger = integerStr.substring(0, length - 4);}return Integer.parseInt(subInteger) > 0;} else {return false;}}五、代码测试阿拉伯数字中包含 "0"的测试特殊情况的测试(特殊字符、负数、超过⼈民币数值范围)。

java阿拉伯数字转中文数字

java阿拉伯数字转中文数字

java阿拉伯数字转中⽂数字本⽂实例为⼤家分享了java阿拉伯数字转换成中⽂数字的具体代码,供⼤家参考,具体内容如下package org.lulu.learn.work;import java.io.*;/*** Project: Day07* Created: Lulu* Date: 2016/8/5*/public class Work02 {public static void main(String[] args) {// int num = 0;// System.out.println(tranWan(num));try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("res/data.txt")));BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("res/result.txt")))){String str = "";int percent = 0;while ((str = br.readLine()) != null) {bw.write(tranWan(Integer.parseInt(str)));bw.newLine();percent++;Thread.sleep(100);System.out.print("\r[");for (int i = 0; i < 20; i++) {if(i < percent/5){System.out.print("=");}else if(i == percent/5){System.out.print(">");}else{System.out.print(" ");}}System.out.print("]");System.out.printf("\t%.2f%%", (float)percent);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();}}/*** 处理千万数字⽅法** @param num* @return*/private static String tranWan(int num) {StringBuilder builder = new StringBuilder();if (num / 10000 > 0) {//说明builder.append(trans(num / 10000)).append("万");}int temp = num % 10000;if (temp > 0) {String trans = trans(temp);//⾸先判断是否有万位,if (builder.length() > 0) {//如果千位为0, 则需要补零if (temp / 1000 == 0) {builder.append("零");}}builder.append(trans);}if (builder.length() == 0) {builder.append("零");}return builder.toString();}/*** 完成4位数转换** @param num* @return*/private static String trans(int num) {String[] numeric = new String[]{"零", "⼀", "⼆", "三", "四", "五", "六", "七", "⼋", "九"}; StringBuilder builder = new StringBuilder();builder.append(numeric[num / 1000] + "千").append(numeric[num / 100 % 10] + "百").append(numeric[num / 10 % 10] + "⼗").append(numeric[num % 10]);//去掉了零千....int index = -1;while ((index = builder.indexOf(numeric[0], index + 1)) != -1) {if (index < builder.length() - 1) {builder.deleteCharAt(index + 1);}}//去掉双零index = 0;while ((index = builder.indexOf("零零", index)) != -1) {builder.deleteCharAt(index);}if (builder.length() > 1) {//去掉开头的零if (builder.indexOf(numeric[0]) == 0) {builder.deleteCharAt(0);}//去掉末尾的零if (builder.indexOf(numeric[0]) == builder.length() - 1) {builder.deleteCharAt(builder.length() - 1);}}//把开头⼀⼗换成⼗if (builder.indexOf("⼀⼗") == 0) {builder.deleteCharAt(0);}return builder.toString();}}再为⼤家分享⼀段:java实现阿拉伯数字转换为汉字数字private static String toChinese(String str) {String[] s1 = { "零", "⼀", "⼆", "三", "四", "五", "六", "七", "⼋", "九" };String[] s2 = { "⼗", "百", "千", "万", "⼗", "百", "千", "亿", "⼗", "百", "千" };String result = "";int n = string.length();for (int i = 0; i < n; i++) {int num = string.charAt(i) - '0';if (i != n - 1 && num != 0) {result += s1[num] + s2[n - 2 - i];} else {result += s1[num];}System.out.println(" "+result);}System.out.println(result);return result;}public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.println("输⼊字符串:");String str = scanner.next();// 将字符串数字转化为汉字toChinese(str);}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

java传入金额转化成大写

java传入金额转化成大写
if(len==temp.length()-2) result=result.concat("零分");
return result;
}
}
int len=0;
if(temp.indexOf(".")==-1) len=temp.length();
else len=temp.indexOf(".");
if(len>s4.length()-3) return("输入字串最大只能精确到仟亿,小数点只能两位!");
public String NumberToChinese(S肆伍陆柒捌玖";
String s4="分角整元拾佰仟万拾佰仟亿拾佰仟";
String temp="";
int n1=0;
String num="";
String unit="";
for(int i=0;i<temp.length();i++){
if(i>len+2){break;}
unit=s4.substring(n1,n1+1);
result=result.concat(num).concat(unit);
}
if((len==temp.length())||(len==temp.length()-1)) result=result.concat("整");
float f;
try{
f=Float.parseFloat(temp);
}catch(Exception e){

java实现将数字转换成人民币大写

java实现将数字转换成人民币大写

java实现将数字转换成⼈民币⼤写Rmb.javapublic class Rmb{/***⼈民币的基本信息和操作*@author weinee*@version 1.0*/double number; //⼈民币的数量private String[] hanArr = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };//汉字计数符号private String[] unitArr = {"", "拾", "佰", "仟"};//汉字计数单位private String[] unitArrs = {"万", "亿", "万", "兆", "万", "亿", "万", "圆"}; //顺序添加单位//private String[] unitsArr = {"万", "亿"}; //汉字计数⼤单位public Rmb(){}/***构造器初始化⼈民币数量*@param 给定的初始化⼈民币数*/public Rmb(double number){this.number = number;}/***把⼀个浮点数分解成long型部分和⼩数部分字符串,把⼈民币换成了整数,浮点数在取⼩数部分时临界值有误差*@return 返回分解后的字符串数组,第⼀个数组元素是整数部分,第⼆个是⼩数部分字符串*/public String[] divideNum(){double num = Math.round(number*100);//对number进⾏四舍五⼊取整long integerPart = (long)num; //连同⼩数点后两位取成整数,避免使⽤减法//double decimalsPart = num-integerPart;//⼩数部分,临界时产⽣了误差String decimalsPartStr;long b = integerPart % 10; //⼩数点后第⼆位long a = (integerPart/10) % 10;//⼩数点后第⼀位integerPart /= 100;if(a==0 && b==0){decimalsPartStr = null;}else{decimalsPartStr = "" + a + b;}return new String[] {String.valueOf(integerPart) , decimalsPartStr};}/***把⼀个数字字符转换成汉语的⼈民币读法*@return 返回汉语⼈民币读法的字符串形式*/public String toHanStr(){String[] results = new String[9]; //⽤来暂时存储每四位分段后的数字字符串String[] resultStrs = new String[9];//⽤来暂时存储每四位分段后转换成的⼈民币读法String result = "";//最终的转换结果String[] divideStr = divideNum(); //得到浮点数分解成的long型部分和⼩数部分字符串,第⼀个数组元素是整数部分字符串,第⼆个是⼩数部分字符串 results[8] = divideStr[1];for (int i=divideStr[0].length(), j=8; i>0&&j>0 ; i-=4,j--){try{results[j-1] = divideStr[0].substring(i-4, i);}catch(Exception e){results[j-1] = divideStr[0].substring(0, i);break;}}if(results[8] == null){resultStrs[8] = "整";}else if(results[8].charAt(1) == '0'){resultStrs[8] = hanArr[results[8].charAt(0) - 48] + "⾓"; //根据ASCII码和hanArr数组吧数字改成汉语⼤写}else{resultStrs[8] = hanArr[results[8].charAt(0) - 48] + "⾓" + hanArr[results[8].charAt(1) - 48] + "分";}for(int i=0; i<8; i++){if(results[i] != null){resultStrs[i] = "";resultStrs[i] += hanArr[results[i].charAt(0) - 48] + unitArr[results[i].length() - 1]; //根据ASCII码和数组长度选择数的单位for (int j=1; j<results[i].length(); j++ )if(results[i].charAt(j-1) == '0' && results[i].charAt(j) != '0')resultStrs[i] += "零" + hanArr[results[i].charAt(j) - 48] + unitArr[results[i].length() - 1 - j]; //根据ASCII码和数组长度选择数的单位 else if(results[i].charAt(j) != '0' )resultStrs[i] += hanArr[results[i].charAt(j) - 48] + unitArr[results[i].length() - 1 - j];}}for (int i=0; i<8; i++ ){if(resultStrs[i] != null){result += resultStrs[i] + unitArrs[i];}}result += resultStrs[8];return result;}}RmbTest.javapublic class RmbTest{public static void main(String[] args){double l;byte[] bye = new byte[50];System.out.println("请输⼊要转换的⼈民币数量:");try{System.in.read(bye);}catch(Exception e){}String s = new String(bye);l = Double.parseDouble(s);Rmb r = new Rmb(l);s = r.toHanStr();System.out.println(s);}}以上所述就是本⽂的全部内容了,希望对⼤家学习java能够有所帮助。

用java代码将金额转换成中文大写

用java代码将金额转换成中文大写

import java.util.regex.Matcher;import java.util.regex.Pattern;public class getChinestMoney {public static void main(String[] args) {System.out.println("原金额为:154846244.20");System.out.println("转换后的金额为:");System.out.println(ChineseMoney("154846244.20"));}/*** 获得中文大写的金额的整数和小数部分* @param money* @return*/public static String ChineseMoney(String money) {String text = transChineseMoney1(money) + transChineseMoney2(money);//"Pattern.CASE_INSENSITIVE"表示不对大小写进行区分Pattern p = pile("零分",Pattern.CASE_INSENSITIVE);Matcher m = p.matcher(text);text = m.replaceAll("");return text;}/*** 截取金额的整数部分,并将其转换成中文大写格式* @return*/public static String transChineseMoney1(String s){ String ss = s;String tmpnewchar = "";//以“.”将ss分成两段,part[0]为整数部分,part[1]为小数部分 String[] part = ss.split("\\.");if (part[0].length() > 10) {// 超出可转换位数return"";}for (int i = 0; i < part[0].length(); i++) {char perchar = part[0].charAt(i);if (perchar == '0')tmpnewchar = tmpnewchar + "零";if (perchar == '1')tmpnewchar = tmpnewchar + "壹";if (perchar == '2')tmpnewchar = tmpnewchar + "贰";if (perchar == '3')tmpnewchar = tmpnewchar + "叁";if (perchar == '4')tmpnewchar = tmpnewchar + "肆";if (perchar == '5')tmpnewchar = tmpnewchar + "伍";if (perchar == '6')tmpnewchar = tmpnewchar + "陆";if (perchar == '7')tmpnewchar = tmpnewchar + "柒";if (perchar == '8')tmpnewchar = tmpnewchar + "捌";if (perchar == '9')tmpnewchar = tmpnewchar + "玖";int j = part[0].length() - i - 1;if (j == 0)tmpnewchar = tmpnewchar + "圆";if (j == 1 && perchar != 0)tmpnewchar = tmpnewchar + "拾";if (j == 2 && perchar != 0)tmpnewchar = tmpnewchar + "佰";if (j == 3 && perchar != 0)tmpnewchar = tmpnewchar + "仟";if (j == 4 && perchar != 0)tmpnewchar = tmpnewchar + "万";if (j == 5 && perchar != 0)tmpnewchar = tmpnewchar + "拾";if (j == 6 && perchar != 0)tmpnewchar = tmpnewchar + "佰";if (j == 7 && perchar != 0)tmpnewchar = tmpnewchar + "仟";if (j == 8 && perchar != 0)tmpnewchar = tmpnewchar + "亿";if (j == 9 && perchar != 0)tmpnewchar = tmpnewchar + "拾";}return tmpnewchar;}/*** 截取金额的小数部分,并将其转换成中文大写格式* @return*/public static String transChineseMoney2(String s) {String ss = s;String tmpnewchar1 = "";String[] part = ss.split("\\.");if (ss.indexOf(".") != -1) {if (part[1].length() > 2) {// MessageDialog.openInformation(null,"提示","小数点之后只能保留两位,系统将自动截段");part[1] = part[1].substring(0, 2);}for (int i = 0; i < part[1].length(); i++) {char perchar = part[1].charAt(i);// System.out.println(perchar);if (perchar == '0')tmpnewchar1 = tmpnewchar1 + "零";if (perchar == '1')tmpnewchar1 = tmpnewchar1 + "壹";if (perchar == '2')tmpnewchar1 = tmpnewchar1 + "贰";if (perchar == '3')tmpnewchar1 = tmpnewchar1 + "叁";if (perchar == '4')tmpnewchar1 = tmpnewchar1 + "肆";if (perchar == '5')tmpnewchar1 = tmpnewchar1 + "伍";if (perchar == '6')tmpnewchar1 = tmpnewchar1 + "陆";if (perchar == '7')tmpnewchar1 = tmpnewchar1 + "柒";if (perchar == '8')tmpnewchar1 = tmpnewchar1 + "捌";if (perchar == '9')tmpnewchar1 = tmpnewchar1 + "玖";if (i == 0 && perchar != 0)tmpnewchar1 = tmpnewchar1 + "角";if (i == 1 && perchar != 0)tmpnewchar1 = tmpnewchar1 + "分"; }}return tmpnewchar1;}}。

将数字转换成中文金额大写形式(Java版)

将数字转换成中文金额大写形式(Java版)
}
return s;
}
/**
* 把传入的数转换为中文金额大写形式
* @param flag int 标志位,1 表示转换整数部分,0 表示转换小数部分
* @param s String 要转换的字符串
* @return 转换好的带单位的中文金额大写形式
*/
private String numFormat(int flag, String s) {
/**
* 把已经转换好的中文金额大写形式加以改进,清理这个字
* 符串里面多余的零,让这个字符串变得更加可观
* 注:传入的这个数应该是经过 splitNum() 方法进行处理,这个字
* 符串应该已经是用中文金额大写形式表示的
* @param s String 已经转换好的字符串
* @return 改进后的字符串
if(this.checkNum(s)) {
return s;
} else {
return "";
}
}
/**
* 判断用户输入的数据是否合法,用户只能输入大于零的数字,不能输入其它字符
* @param s String
* @return 如果用户输入数据合法,返回 true,否则返回 false
// 拾万位到仟万位
"拾", "佰", "仟",
// 亿位到万亿位
"亿", "拾", "佰", "仟", "万"};
String small[] = {"分", "角"};

阿拉伯数字转换成中文大写数字的java类

阿拉伯数字转换成中文大写数字的java类
chineseStr = chineseStr + chineseDigits[numJiao] + "角" + chineseDigits[numFen] + "分";
}
return chineseStr;
}
/**
*把一个0~9999之间的整数转换为汉字的字符串,如果是0则返回""
* @param amountPart
boolean lastIsZero = true; //在从低位往高位循环时,记录上一位数字是不是0
String chineseStr = "";
for(int i=0; i<amountStrLength; i++) {
if(temp == 0) //高位已无数据
break;
int digit = temp % 10;
lastIsZero = false;
}
temp = temp / 10;
}
return chineseStr;
}
public static void main(String[] args) {
if(args.length == 0) {
System.out.println("转换演示:");
System.out.println("-------------------------");
阿拉伯数字转换成中文大写数字的java类
public classAtoC{
public static String[] chineseDigits = new String[] { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};

数字转汉字方法

数字转汉字方法

在中文中,将阿拉伯数字转换成汉字的过程通常被称为“数字转换成中文大写”或者“数字转换成汉字”。

在中文书写或者印刷金额大写、日期、计量单位等场合常常用到这种转换。

以下是将数字转换成中文大写的一般方法:
1. 将阿拉伯数字按照中文读数的规则转换成对应的汉字。

例如,把123 转成一百二十三。

2. 分段处理。

首先将整数部分转换为大写,然后转换小数部分(如果有)。

3. 要特别注意一些特殊情况,例如十的读法视具体情况而定,如一十一和十一的区别。

在编程中,可以通常使用以下逻辑来实现数字转换成中文大写的功能:
1. 将数字按照千、百、十、个位分解,依次转换成对应的中文大写字符。

2. 考虑零的处理,例如连续的零只保留一个。

3. 如果需要处理小数部分,则将小数部分转换成对应的角、分、厘等单位。

虽然这个功能在实际应用中可能显得简单,但需要考虑到中文读数的复杂性和一些特殊规则,确保计算结果的准确性和规范性。

阿拉伯数字的金额转换成中国传统的形式_java算法

阿拉伯数字的金额转换成中国传统的形式_java算法

package test.format;import java.text.NumberFormat;import java.util.HashMap;public class SimpleMoney Format {public static final String EMPTY = "";public static final String ZERO = "零";public static final String ONE = "壹";public static final String TWO = "贰";public static final String THREE = "叁";public static final String FOUR = "肆";public static final String FIVE = "伍";public static final String SIX = "陆";public static final String SEVEN = "柒";public static final String EIGHT = "捌";public static final String NINE = "玖";public static final String TEN = "拾";public static final String HUNDRED = "佰";public static final String THOUSAND = "仟";public static final String TEN_THOUSAND = "万";public static final String HUNDRED_MILLION = "亿";public static final String YUAN = "元";public static final String JIAO = "角";public static final String FEN = "分";public static final String DOT = ".";private static SimpleMoney Format formatter = null;private HashMap chineseNumberMap = new HashMap();private HashMap chineseMoney Pattern = new HashMap();private NumberFormat numberFormat = NumberFormat.getInstance(); private SimpleMoneyFormat() {numberFormat.setMaximumFractionDigits(4);numberFormat.setMinimumFractionDigits(2);numberFormat.setGroupingUsed(false);chineseNumberMap.put("0", ZERO);chineseNumberMap.put("1", ONE);chineseNumberMap.put("2", TWO);chineseNumberMap.put("3", THREE);chineseNumberMap.put("4", FOUR);chineseNumberMap.put("5", FIVE);chineseNumberMap.put("6", SIX);chineseNumberMap.put("7", SEVEN);chineseNumberMap.put("8", EIGHT);chineseNumberMap.put("9", NINE);chineseNumberMap.put(DOT, DOT);chineseMoney Pattern.put("1", TEN);chineseMoney Pattern.put("2", HUNDRED);chineseMoney Pattern.put("3", THOUSAND);chineseMoney Pattern.put("4", TEN_THOUSAND);chineseMoney Pattern.put("5", TEN);chineseMoney Pattern.put("6", HUNDRED);chineseMoney Pattern.put("7", THOUSAND);chineseMoney Pattern.put("8", HUNDRED_MILLION);}public static SimpleMoneyFormat getInstance() {if (formatter == null)formatter = new SimpleMoneyFormat();return formatter;}public String format(String money Str) {checkPrecision(money Str);String result;result = convertToChineseNumber(money Str);result = addUnitsToChineseMoney String(result);return result;}public String format(double money Double) {return format(numberFormat.format(money Double));}public String format(int moneyInt) {return format(numberFormat.format(moneyInt));}public String format(long money Long) {return format(numberFormat.format(money Long));}public String format(Number money Num) {return format(numberFormat.format(money Num));}private String convertToChineseNumber(String money Str) {String result;StringBuffer cMoney StringBuffer = new StringBuffer();for (int i = 0; i < money Str.length(); i++) {cMoney StringBuffer.append(chineseNumberMap.get(money Str.substring(i, i + 1)));}//拾佰仟万亿等都是汉字里面才有的单位,加上它们int indexOfDot = cMoney StringBuffer.indexOf(DOT);int money PatternCursor = 1;for (int i = indexOfDot - 1; i > 0; i--) {cMoney StringBuffer.insert(i, chineseMoney Pattern.get(EMPTY + money PatternCursor)); money PatternCursor = money PatternCursor == 8 ? 1 : moneyPatternCursor + 1;}String fractionPart = cMoney StringBuffer.substring(cMoney StringBuffer.indexOf(".")); cMoney StringBuffer.delete(cMoney StringBuffer.indexOf("."), cMoney StringBuffer.length()); while (cMoney StringBuffer.indexOf("零拾") != -1) {cMoney StringBuffer.replace(cMoney StringBuffer.indexOf("零拾"), cMoney StringBuffer.indexOf("零拾") + 2, ZERO);}while (cMoney StringBuffer.indexOf("零佰") != -1) {cMoney StringBuffer.replace(cMoney StringBuffer.indexOf("零佰"), cMoney StringBuffer.indexOf("零佰") + 2, ZERO);}while (cMoney StringBuffer.indexOf("零仟") != -1) {cMoney StringBuffer.replace(cMoney StringBuffer.indexOf("零仟"), cMoney StringBuffer.indexOf("零仟") + 2, ZERO);}while (cMoney StringBuffer.indexOf("零万") != -1) {cMoney StringBuffer.replace(cMoney StringBuffer.indexOf("零万"), cMoney StringBuffer.indexOf("零万") + 2, TEN_THOUSAND);}while (cMoney StringBuffer.indexOf("零亿") != -1) {cMoney StringBuffer.replace(cMoney StringBuffer.indexOf("零亿"), cMoney StringBuffer.indexOf("零亿") + 2, HUNDRED_MILLION);}while (cMoney StringBuffer.indexOf("零零") != -1) {cMoney StringBuffer.replace(cMoney StringBuffer.indexOf("零零"), cMoney StringBuffer.indexOf("零零") + 2, ZERO);}if (cMoney stIndexOf(ZERO) == cMoney StringBuffer.length() - 1)cMoney StringBuffer.delete(cMoney StringBuffer.length() - 1, cMoney StringBuffer.length()); cMoney StringBuffer.append(fractionPart);result = cMoney StringBuffer.toString();return result;}private String addUnitsToChineseMoney String(String money Str) {String result;StringBuffer cMoney StringBuffer = new StringBuffer(money Str);int indexOfDot = cMoney StringBuffer.indexOf(DOT);cMoney StringBuffer.replace(indexOfDot, indexOfDot + 1, Y UAN);。

java数字转换成汉字

java数字转换成汉字

java数字转换成汉字public class Wdfdd {public static void main(String[] args) {String[] cnChar={"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};double shuzi=5001110.012;long a=(int)shuzi;String[] cnUtuis={"","十","百","千","万","十","百","千","亿"};String [] cnDecianls={"角","分","毫"};//String[] cnDanwei={"万","亿"};String str=a+" ";//数字转换成字符串的最简单方法String result=" "; //直接加一个空字符//str.length返回的是字符的个数//循环从0~str的字符个数减1//System.out.println(str);byte zeroNum=0;//连续零的个数int q=0;for (int i=str.length()-2,j=0,e=1;i>=0;i-- ){char NumChar=str.charAt(i);//返回字符串的第i个位置的字符。

//System.out.println(NumChar);//如果当前的位置是零的话无需添加单//if(j==4*e+1){// result=cnchar[NumChar-48]+cnUtuis[j]+cnDanwei[e-1]+result;//}if(NumChar=='0'){zeroNum++;if(zeroNum<2){//如果有两个以上的连续零时将当做一个零if(j==4){result=cnUtuis[j]+result;}else{result=cnChar[NumChar-48]+result;}}else{q++;//省略的0个数;}}else{result=cnChar[NumChar-48]+cnUtuis[j]+result; zeroNum=0;}j++;}if(result.length()>str.length()-q-1){result=result.substring(0, result.length()-2);}else if(result.length()>str.length()-q-1){result=result.substring(0,result.length()-2);}//小数部分String result1=" ";float decimalsPlace=(float)(shuzi-a);String decianlsChar=decimalsPlace+" ";decianlsChar=decianlsChar.substring(2,decianlsChar.length()-1);for(int i=0;i<decianlschar.length();i++){char NumChar=decianlsChar.charAt(i);if(NumChar!='0'){result1+=cnChar[NumChar-48]+cnDecianls[i];}}result=result+result1;//System.out.print(decianlsChar);System.out.print(result);}}</decianlschar.length();i++){。

Java将数字金额转为大写中文金额

Java将数字金额转为大写中文金额

Java将数字⾦额转为⼤写中⽂⾦额本⽂实例为⼤家分享了Java如何将数字⾦额转为⼤写中⽂⾦额的具体代码,供⼤家参考,具体内容如下前⾔:输⼊数字⾦额参数,运⾏程序得到其对应的⼤写中⽂⾦额;例如:输⼊— 12.56,输出— 12.56:壹拾贰元伍⾓陆分;重点来了:本⼈亲测有效。

奉上代码:/***@Title: ConvertUpMoney* @Description: 将数字⾦额转为⼤写汉字⾦额* @date: 2019年6⽉18⽇下午10:52:27*/public class ConvertUpMoney {//⼤写数字private static final String[] NUMBERS = {"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};// 整数部分的单位private static final String[] IUNIT = {"元","拾","佰","仟","万","拾","佰","仟","亿","拾","佰","仟","万","拾","佰","仟"};//⼩数部分的单位private static final String[] DUNIT = {"⾓","分","厘"};//转成中⽂的⼤写⾦额public static String toChinese(String str) {//判断输⼊的⾦额字符串是否符合要求if (StringUtils.isBlank(str) || !str.matches("(-)?[\\d]*(.)?[\\d]*")) {System.out.println("抱歉,请输⼊数字!");return str;}if("0".equals(str) || "0.00".equals(str) || "0.0".equals(str)) {return "零元";}//判断是否存在负号"-"boolean flag = false;if(str.startsWith("-")){flag = true;str = str.replaceAll("-", "");}str = str.replaceAll(",", "");//去掉","String integerStr;//整数部分数字String decimalStr;//⼩数部分数字//初始化:分离整数部分和⼩数部分if(str.indexOf(".")>0) {integerStr = str.substring(0,str.indexOf("."));decimalStr = str.substring(str.indexOf(".")+1);}else if(str.indexOf(".")==0) {integerStr = "";decimalStr = str.substring(1);}else {integerStr = str;decimalStr = "";}//beyond超出计算能⼒,直接返回if(integerStr.length()>IUNIT.length) {System.out.println(str+":超出计算能⼒");return str;}int[] integers = toIntArray(integerStr);//整数部分数字//判断整数部分是否存在输⼊012的情况if (integers.length>1 && integers[0] == 0) {System.out.println("抱歉,请输⼊数字!");if (flag) {str = "-"+str;}return str;}boolean isWan = isWan5(integerStr);//设置万单位int[] decimals = toIntArray(decimalStr);//⼩数部分数字String result = getChineseInteger(integers,isWan)+getChineseDecimal(decimals);//返回最终的⼤写⾦额 if(flag){return "负"+result;//如果是负数,加上"负"}else{return result;}}//将字符串转为int数组private static int[] toIntArray(String number) {int[] array = new int[number.length()];for(int i = 0;i<number.length();i++) {array[i] = Integer.parseInt(number.substring(i,i+1));}return array;}//将整数部分转为⼤写的⾦额public static String getChineseInteger(int[] integers,boolean isWan) {StringBuffer chineseInteger = new StringBuffer("");int length = integers.length;if (length == 1 && integers[0] == 0) {return "";}for(int i=0;i<length;i++) {String key = "";if(integers[i] == 0) {if((length - i) == 13)//万(亿)key = IUNIT[4];else if((length - i) == 9) {//亿key = IUNIT[8];}else if((length - i) == 5 && isWan) {//万key = IUNIT[4];}else if((length - i) == 1) {//元key = IUNIT[0];}if((length - i)>1 && integers[i+1]!=0) {key += NUMBERS[0];}}chineseInteger.append(integers[i]==0?key:(NUMBERS[integers[i]]+IUNIT[length - i -1]));}return chineseInteger.toString();}//将⼩数部分转为⼤写的⾦额private static String getChineseDecimal(int[] decimals) {StringBuffer chineseDecimal = new StringBuffer("");for(int i = 0;i<decimals.length;i++) {if(i == 3) {break;}chineseDecimal.append(decimals[i]==0?"":(NUMBERS[decimals[i]]+DUNIT[i]));}return chineseDecimal.toString();}//判断当前整数部分是否已经是达到【万】private static boolean isWan5(String integerStr) {int length = integerStr.length();if(length > 4) {String subInteger = "";if(length > 8) {subInteger = integerStr.substring(length- 8,length -4);}else {subInteger = integerStr.substring(0,length - 4);}return Integer.parseInt(subInteger) > 0;}else {return false;}}//Testpublic static void main(String[] args) {String number = "12.56";System.out.println(number+": "+ConvertUpMoney.toChinese(number));number = "1234567890563886.123";System.out.println(number+": "+ConvertUpMoney.toChinese(number));number = "1600";System.out.println(number+": "+ConvertUpMoney.toChinese(number));number = "156,0";System.out.println(number+": "+ConvertUpMoney.toChinese(number));number = "-156,0";System.out.println(number+": "+ConvertUpMoney.toChinese(number));number = "0.12";System.out.println(number+": "+ConvertUpMoney.toChinese(number));number = "0.0";System.out.println(number+": "+ConvertUpMoney.toChinese(number));number = "01.12";System.out.println(number+": "+ConvertUpMoney.toChinese(number));number = "0125";System.out.println(number+": "+ConvertUpMoney.toChinese(number));number = "-0125";System.out.println(number+": "+ConvertUpMoney.toChinese(number));number = "sdw5655";System.out.println(number+": "+ConvertUpMoney.toChinese(number));System.out.println(null+": "+ConvertUpMoney.toChinese(null));}}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

java实现整数转化为中文大写金额的方法

java实现整数转化为中文大写金额的方法

java实现整数转化为中⽂⼤写⾦额的⽅法在⽇常⽣活中,我们经常会将阿拉伯数字转化为中⽂⼤写的情况:"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖", "拾", "佰", "仟", "万", "亿",因此⾃⼰就编写⼀个类,实现该功能的转化。

实现过程:对于这个问题的实现,我们⾸先把数字按四位⼀个拆开(符合我们读数字的习惯),然后对这四位数,做出他的读法,具体代码如下:private static String getNumberStr1000 (int num) {if (num > 9999 || num < 0) {return "";}int q = num / 1000;int b = (num / 100) % 10;int s = (num / 10) % 10;int g = num % 10;StringBuffer sb = new StringBuffer();//千if (q > 0) {sb.append(NUMBER1[q]);sb.append(NUMBER2[3]);}//百if (b > 0) {sb.append(NUMBER1[b]);sb.append(NUMBER2[2]);} else {if (q != 0) {sb.append(NUMBER2[0]);}}//⼗if (s > 0) {sb.append(NUMBER1[s]);sb.append(NUMBER2[1]);} else {if (b != 0) {sb.append(NUMBER2[0]);}}//个if (g > 0) {sb.append(NUMBER1[g]);}return sb.toString();}下⾯我们只需要在编写⼀个⽅法,实现每个四位数的读法以及对应的单位即可,具体代码如下:public static String getNumberStr(int num) {if (num < 0) {return "";}if (num == 0) {return NUMBER1[0];}int split = 10000;int y = num / (split * split);int w = (num / split) % split;int g = num % split;StringBuffer sb = new StringBuffer();//亿if (y > 0) {sb.append(getNumberStr1000(y));sb.append(NUMBER2[5]);}//万if (w > 999) {sb.append(getNumberStr1000(w));sb.append(NUMBER2[4]);} else {if (w > 0) {if (y != 0) {sb.append(NUMBER2[0]);}sb.append(getNumberStr1000(w));sb.append(NUMBER2[4]);}}//万以下if (g > 0) {if (w != 0) {if (g > 999) {sb.append(getNumberStr1000(g));} else {sb.append(NUMBER2[0]);sb.append(getNumberStr1000(g));}} else {if (y != 0) {sb.append(NUMBER2[0]);}sb.append(getNumberStr1000(g));}}return sb.toString();}完整源代码:/***@Description:*/package com.lulei.util;public class NumberUtil {private static String[] NUMBER1 = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"}; private static String[] NUMBER2 = {"零", "拾", "佰", "仟", "万", "亿"};/*** @param num* @return* @Author:lulei* @Description:将数字转化为⼤写*/public static String getNumberStr(int num) {if (num < 0) {return "";}if (num == 0) {return NUMBER1[0];}int split = 10000;int y = num / (split * split);int w = (num / split) % split;int g = num % split;StringBuffer sb = new StringBuffer();//亿if (y > 0) {sb.append(getNumberStr1000(y));sb.append(NUMBER2[5]);}//万if (w > 999) {sb.append(getNumberStr1000(w));sb.append(NUMBER2[4]);} else {if (w > 0) {if (y != 0) {sb.append(NUMBER2[0]);}sb.append(getNumberStr1000(w));sb.append(NUMBER2[4]);}}//万以下if (g > 0) {if (w != 0) {if (g > 999) {sb.append(getNumberStr1000(g));} else {sb.append(NUMBER2[0]);sb.append(getNumberStr1000(g));}} else {if (y != 0) {sb.append(NUMBER2[0]);}sb.append(getNumberStr1000(g));}}return sb.toString();}/*** @param num* @return* @Description:对万以下的数字进⾏⼤⼩写转化*/private static String getNumberStr1000 (int num) {if (num > 9999 || num < 0) {return "";}int q = num / 1000;int b = (num / 100) % 10;int s = (num / 10) % 10;int g = num % 10;StringBuffer sb = new StringBuffer();//千if (q > 0) {sb.append(NUMBER1[q]);sb.append(NUMBER2[3]);}//百if (b > 0) {sb.append(NUMBER1[b]);sb.append(NUMBER2[2]);} else {if (q != 0) {sb.append(NUMBER2[0]);}}//⼗if (s > 0) {sb.append(NUMBER1[s]);sb.append(NUMBER2[1]);} else {if (b != 0) {sb.append(NUMBER2[0]);}}//个if (g > 0) {sb.append(NUMBER1[g]);}return sb.toString();}public static void main(String[] args) {// TODO Auto-generated method stubint i = 1;System.out.println(i + "--" + NumberUtil.getNumberStr(i));i = 1001;System.out.println(i + "--" + NumberUtil.getNumberStr(i));i = 100101;System.out.println(i + "--" + NumberUtil.getNumberStr(i));i = 10100101;System.out.println(i + "--" + NumberUtil.getNumberStr(i));i = 1234567890;System.out.println(i + "--" + NumberUtil.getNumberStr(i)); }}测试运⾏结果:希望本⽂所述对⼤家学习java程序设计有所帮助。

将阿拉伯数字金额转换成中文大写数字金额的转换类money_convert

将阿拉伯数字金额转换成中文大写数字金额的转换类money_convert

package com.newer;/** To change this template, choose Tools | Templates* and open the template in the editor.*///package mon;import java.math.RoundingMode;import java.text.NumberFormat;import java.util.HashMap;import java.util.Map;/*** 将阿拉伯数字金额转换成中文大写数字金额的转换类* @author yzy*/public class MoneyConvert {* 将阿拉伯数字金额转换成中文大写数字金额* @param money * @returnpublic static String toCNMoney(double money) {//转换成指定格式的数字NumberFormat fmt = NumberFormat.getInstance();fmt.setMaximumFractionDigits(2);//两位小数fmt.setRoundingMode(RoundingMode.HALF_UP); //四舍五入fmt.setGroupingUsed(false);//不要千分号money = Double.valueOf(fmt.format(money));Map<Integer, String> numbersMap = new HashMap<Integer, String>(10);String[] section = {"", "萬", "億", "兆"};//拆分为四大块,精确到万亿位,即兆// String[] positions = {"拾", "佰", "仟"};String[] numbers = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};for (int i = 0; i < numbers.length; i++) {numbersMap.put(i, numbers[i]);}String result = "";//1.处理小数位(如果有)if (fmt.format(money).contains(".")) {int remainder = (int) ((money * 100) % 100);//取余int a = remainder / 10;if (a != 0) {result = numbersMap.get(a) + "角";}int b = remainder % 10;if (b != 0) {if (a == 0) {result += numbersMap.get(0) + numbersMap.get(b) + "分";//处理特殊情况,如2.05(贰圆零伍分)} else {result += numbersMap.get(b) + "分";} } }//2.处理整数位long total = (long) (money * 100 / 100);//取整if (total == 0) {return result.equals("") ? (numbersMap.get(0) + "圆") : result;//少于1元} int j = 0; String tempResult = "";do { //每次处理四位数long t = (total % 10000);String str = MoneyConvert.thousandToUpperCase((int) t, numbersMap, null);total = total / 10000;if (total != 0 && t > 0 && t < 1000) {str = numbersMap.get(0) + str;//如果每次处理之后还有万位且前次处理的四位取余t(0<t<1000),则前面应补零}tempResult = str + section[j] + tempResult; j++;} while (total != 0);//3.最后别忘了金额单位result = tempResult + "圆" + result;return result; }/处理千位以内阿拉伯数字金额*@param number*@param numbersMap*@param result* @return */private static String thousandToUpperCase(int number, Map<Integer, String> numbersMap, String result) { result = result == null ? "" : result;if (number < 10) { return number == 0 ? result : (result + numbersMap.get(number));//取出个位}if (number < 100) {result = result + numbersMap.get(number / 10) + "拾";//取出十位return thousandToUpperCase(number % 10, numbersMap, result); } if (number < 1000) {result = result + numbersMap.get(number / 100) + "佰";//取出百位//处理特殊情况,如201if (0 < number % 100 && number % 100 < 10) {result += numbersMap.get(0);//加个零}return thousandToUpperCase(number % 100, numbersMap, result); } if (number < 10000) {result = result + numbersMap.get(number / 1000) + "仟";//取出千位//处理特殊情况,如2001,2011if (0 < number % 1000 && number % 1000 < 100) {result += numbersMap.get(0);//加个零}return thousandToUpperCase(number % 1000, numbersMap, result); } return result; }public static void main(String[] args) {System.out.println(MoneyConvert.toCNMoney(1010101010101.00));System.out.println(MoneyConvert.toCNMoney(100.00));}}。

中文金额大小写转换公式模板

中文金额大小写转换公式模板

中文金额大小写转换公式模板```#定义数字字符对应的中文大写字符digits = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']#定义单位字符对应的中文大写字符units = ['', '拾', '佰', '仟', '万', '亿']#将阿拉伯数字表示的金额转换为中文表示的金额def convert_amount_to_chinese(amount):#将金额转换为字符串amount_str = str(amount)#判断金额是否合法if not amount_str.isdigit(:return '金额不合法'#去除金额首部的零amount_str = amount_str.lstrip('0')#如果金额为0,直接返回“零元整”if amount_str == '0':return '零元整'#分割金额的整数部分和小数部分integer_part, decimal_part = amount_str.split('.') #转换整数部分的金额chinese_amount =convert_integer_part_to_chinese(integer_part) + '元' #当小数部分为00时,添加“整”if decimal_part == '00':chinese_amount += '整'else:#转换小数部分的金额chinese_amount +=convert_decimal_part_to_chinese(decimal_part) return chinese_amount#将整数部分的金额转换为中文表示def convert_integer_part_to_chinese(integer_part): #反转整数部分字符串,便于从低位到高位处理integer_part = integer_part[::-1]#初始化中文表示的整数部分金额字符串chinese_amount = ''#判断整数部分是否为零if integer_part == '0':return '零'#迭代处理整数部分的每一位for i, digit in enumerate(integer_part):#当前数字为零时,如果下一位数字也为零,则跳过if digit == '0' and i + 1 < len(integer_part) andinteger_part[i + 1] == '0':continue#获取当前数字的中文大写字符digit_char = digits[int(digit)]#获取当前数字的单位字符unit_char = units[i % 4]#如果当前数字为零且单位字符不为空,则在金额后添加单位字符if digit == '0' and unit_char != '':chinese_amount = digit_char + chinese_amount#如果当前数字不为零,则在金额后添加当前数字和单位字符elif digit != '0':chinese_amount = digit_char + unit_char + chinese_amount#如果当前数字不为零且单位字符不为空,则在金额后添加零if digit != '0' and unit_char != '':chinese_amount = digits[0] + chinese_amountreturn chinese_amount#将小数部分的金额转换为中文表示def convert_decimal_part_to_chinese(decimal_part):#获取小数部分的十位和个位数字ten_digit = decimal_part[0]one_digit = decimal_part[1]#初始化中文表示的小数部分金额字符串chinese_amount = ''#根据小数部分的十位和个位数字转换为中文表示if ten_digit != '0':chinese_amount += digits[int(ten_digit)] + '角'if one_digit != '0':chinese_amount += digits[int(one_digit)] + '分' return chinese_amount```请注意,该公式模板仅适用于转换人民币金额,不适用于其他货币单位。

Java阿拉伯数字转换为中文大写数字

Java阿拉伯数字转换为中文大写数字

Java阿拉伯数字转换为中⽂⼤写数字Java 阿拉伯数字转换为中⽂⼤写数字/*** <html>* <body>* <P> Copyright 1994 JsonInternational</p>* <p> All rights reserved.</p>* <p> Created on 19941115</p>* <p> Created by Jason</p>* </body>* </html>*/package cn.ucaner.alpaca.framework.utils.chinese;import java.text.DecimalFormat;import java.util.HashMap;import java.util.Map;import cn.ucaner.alpaca.framework.utils.string.StringHelper;/*** @Package:cn.ucaner.framework.utils* @ClassName:ChineseNumber* @Description: <p> 阿拉伯数字转换为中⽂⼤写数字. </p>* @Author: - Jason* @CreatTime:2017年8⽉30⽇下午2:15:16* @Modify By:* @ModifyTime:* @Modify marker:* @version V1.0*/public class ChineseNumber {private static final String[] BEFORE_SCALE = { "万", "仟", "佰", "拾", "亿", "仟", "佰", "拾", "万", "仟", "佰", "拾", "" };private static final String[] AFTER_SCALE = { "⾓", "分" };private static final String DEFAULT_PATH_SEPARATOR = ".";private static final Map<String, String> NUMBER_MAPPING = new HashMap<String, String>();static {NUMBER_MAPPING.put("0", "零");NUMBER_MAPPING.put("1", "壹");NUMBER_MAPPING.put("2", "贰");NUMBER_MAPPING.put("3", "叁");NUMBER_MAPPING.put("4", "肆");NUMBER_MAPPING.put("5", "伍");NUMBER_MAPPING.put("6", "陆");NUMBER_MAPPING.put("7", "柒");NUMBER_MAPPING.put("8", "捌");NUMBER_MAPPING.put("9", "玖");}public static String getChineseNumber(String number) {return getChineseNumber(number, null, null);}public static String getChineseNumber(String number, String unit, String postfix) {String[] numbers = StringHelper.strToStrArray(number, DEFAULT_PATH_SEPARATOR);if (numbers.length > 2) {new NumberFormatException("数字格式错误!");}int length = numbers[0].length();int isZero = 0;StringBuffer result = new StringBuffer();for (int i = 0; i < length; i++) {String digit = String.valueOf(numbers[0].charAt(i));boolean allZero = true; // 如果后继的全部是零,则跳出for (int j = i; j < length; j++) {if (numbers[0].charAt(j) != '0') {allZero = false;break;}}if (allZero) {boolean hasValue = false;for (int z = i; z >= 0; z--) {if (numbers[0].charAt(z) != '0' && length - z <= 7 && length - z >= 5) {hasValue = true;break;}}// 加万单位if ( ( length - i > 4 && length <= 8 ) || ( hasValue && length - i > 4 )) {result.append(BEFORE_SCALE[8]);}// 加亿单位if (length - i >= 9) {result.append(BEFORE_SCALE[4]);}break;}if (length < 9 && length - i == 5) {if (!"0".equals(digit) && isZero > 0) {result.append(NUMBER_MAPPING.get("0"));}if ("0".equals(digit)) {result.append(BEFORE_SCALE[8]);if (isZero > 0) {result.append(NUMBER_MAPPING.get("0"));}continue;}}if ("0".equals(digit) && length > 9 && length - i == 9) {result.append(BEFORE_SCALE[4]);continue;}if (isZero < 1 || !"0".equals(digit)) {if ("0".equals(digit)) {if (length - i != 6 && length - i != 7) {result.append(NUMBER_MAPPING.get(digit));}} else {result.append(NUMBER_MAPPING.get(digit));}if (!"0".equals(digit)) {result.append(BEFORE_SCALE[BEFORE_SCALE.length - length + i]);}}if ("0".equals(digit)) {isZero++;} else {isZero = 0;}}result.append(unit == null ? "圆" : result.append(unit));if (numbers.length == 1) {result.append(postfix == null ? "整" : result.append(postfix));return result.toString();}length = numbers[1].length();for (int j = 0; j < length; j++) {if (j > 2) {break;}if (numbers[1].charAt(j) == '0') {continue;}result.append(NUMBER_MAPPING.get(String.valueOf(numbers[1].charAt(j)))); result.append(AFTER_SCALE[j]);}result.append(postfix == null ? "整" : result.append(postfix));return result.toString();}public static String getChineseNumber(int number) {return getChineseNumber(new Integer(number));}public static String getChineseNumber(int number, String unit, String postfix) { return getChineseNumber(new Integer(number), unit, postfix);}public static String getChineseNumber(Long number) {return getChineseNumber(number.toString(), null, null);}public static String getChineseNumber(Integer number) {return getChineseNumber(number.toString(), null, null);}public static String getChineseNumber(Integer number, String unit, String postfix) { return getChineseNumber(number.toString(), unit, postfix);}public static String getChineseNumber(Long number, String unit, String postfix) { return getChineseNumber(number.toString(), unit, postfix);}public static String getChineseNumber(long number) {return getChineseNumber(new Long(number));}public static String getChineseNumber(long number, String unit, String postfix) { return getChineseNumber(new Long(number), unit, postfix);}public static String getChineseNumber(double number, String unit, String postfix) { DecimalFormat f = (DecimalFormat) DecimalFormat.getInstance();f.applyLocalizedPattern("#.##");return getChineseNumber(f.format(number), unit, postfix);}public static String getChineseNumber(double number) {return getChineseNumber(number, null, null);}public static String getChineseNumber(Double number) {return getChineseNumber(number.doubleValue());}public static String getChineseNumber(Double number, String unit, String postfix) { return getChineseNumber(number.doubleValue(), unit, postfix);}public static void main(String[] args) {System.out.println(getChineseNumber(1994));System.out.println(getChineseNumber(1994.1115));System.out.println(getChineseNumber(19941115));}}//Outputs//壹仟玖佰玖拾肆圆整//壹仟玖佰玖拾肆圆壹⾓壹分整//壹仟玖佰玖拾肆万壹仟壹佰壹拾伍圆整。

java实现数字转换人民币中文大写工具

java实现数字转换人民币中文大写工具

java实现数字转换⼈民币中⽂⼤写⼯具本⽂实例为⼤家分享了java实现数字转换⼈民币中⽂⼤写的具体代码,供⼤家参考,具体内容如下业务场景:1.在⼈事业务系统开发的报表打印⽂书时经常需要将⼈民币数值转换为⼤写,所以⽤java写了⼀个通⽤的⼤写转换函数。

为了更加⽅便调⽤函数的参数使⽤字符串类型。

例如:825.45 转换后:捌佰贰拾伍元肆⾓伍分2.在⼈事业务系统中经常把⽇期⽤汉字⼤写表⽰,为了⽅便调⽤函数,也是使⽤字符串类型。

例如:2018 转换后:⼆〇⼀⼋下⾯为java代码public class Data2Zh {final static private String NUMBER[] = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };final static private String NUMBER2[] = { "〇", "⼀", "⼆", "三", "四", "五", "六", "七", "⼋", "九" };final static private String CBit[] = { "", "拾", "佰", "仟" };/*** 将数值⼤写*/public static String capitalization(String szNum) {StringBuilder resstr = new StringBuilder();String tmpstr = szNum.trim();int sl = tmpstr.length();int sp = 0;int dotpos = tmpstr.indexOf('.');if (dotpos != -1) {while (sl > 1 && tmpstr.charAt(sl - 1) == '0')sl--;if (tmpstr.charAt(sl - 1) == '.')sl--;if (sl != tmpstr.length()) {tmpstr = tmpstr.substring(0, sl);}} elsedotpos = sl;if (sl < 1)return NUMBER[0];if (tmpstr.charAt(0) == '-') {resstr.append("负");sp = 1;}String integerNum = tmpstr.substring(sp, dotpos - sp);String decimalNum = "";if (dotpos + 1 < sl)decimalNum = tmpstr.substring(dotpos + 1);sl = integerNum.length();sp = 0;while (sp < sl && integerNum.charAt(sp) == '0')sp++;if (sp > 0)integerNum = integerNum.substring(sp);int inl = integerNum.length();if (inl > 0) {int h = (inl - 1) % 4;int j = (inl - 1) / 4 + 1;sp = 0;boolean allzero = false;boolean preallzero = false;for (; j > 0; j--) {int k = h;h = 3;boolean preiszero = allzero;allzero = true;for (; k >= 0; k--, sp++) {if (integerNum.charAt(sp) == '0')preiszero = true;else {allzero = false;if (preiszero)resstr.append("零");preiszero = false;resstr.append(NUMBER[(byte) (integerNum.charAt(sp)) - 48]).append(CBit[k]);}}// end for kif (/* j!=0 && */ j % 2 == 0) {if (!allzero)resstr.append("万");} else {if (!allzero || !preallzero) {int repyi = j / 2;for (int i = 0; i < repyi; i++)resstr.append("亿");}}preallzero = allzero;}// end for j} elseresstr.append("零");int dnl = decimalNum.length();if (dnl > 0) {resstr.append("点");for (int i = 0; i < dnl; i++) {resstr.append(NUMBER[(byte) (decimalNum.charAt(i)) - 48]);}}return resstr.toString();}/*** 获得某⼀位上的数值,如果 nBit<0 则获得⼩数点后⾯的位数*/static public char getNumByte(String szNum, int nBit) {int sl = szNum.length();int nPos = 0;while (nPos < sl && szNum.charAt(nPos) != '.')nPos++;if (nBit < 0)nPos = nPos - nBit;elsenPos = nPos - nBit - 1;if (nPos < 0 || nPos >= sl)return '0';return szNum.charAt(nPos);}public static String rmbChange(String rmb) {return capitalization((rmb.indexOf('.') >= 0 ? rmb.substring(0, rmb.indexOf('.')) : rmb)) + "元" + capitalization(String.valueOf(getNumByte(rmb, -1))) + "⾓"+ capitalization(String.valueOf(getNumByte(rmb, -2))) + "分";}/*** 仅仅是把 0~9 转换为 "〇","⼀","⼆","三","四","五","六","七","⼋","九"*/public static String changeCN(String szNum) {StringBuilder sb = new StringBuilder();String str = szNum.trim();int sl = str.length();int sp = 0;if (sl < 1)return NUMBER2[0];for (; sp < sl; sp++)if (str.charAt(sp) >= '0' && str.charAt(sp) <= '9')sb.append(NUMBER2[str.charAt(sp) - '0']);elsesb.append(str.charAt(sp));return sb.toString();}public static void main(String[] args) {System.out.println(rmbChange("825.45"));System.out.println(changeCN("2018"));}}效果图:以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

将表示金额的阿拉伯数字转换成中文大写形式

将表示金额的阿拉伯数字转换成中文大写形式

将表示金额的阿拉伯数字转换成中文大写形式对于用EXCEL来处理日常统计报表的财务人员来说,一个最令人头痛的问题,就是如何将表示金额的阿拉伯数字转换成中文大写形式。

这里给出将阿拉伯金额数字转换成中文大写形式的两种方法:内置函数法、自定义函数法,供大家参考。

本文所涉及到的Excel函数如下,点击可查阅具体的函数用法。

1、ABS(number)2、CONCATENATE(Text1,Text……)3、INT(number)4、TEXT(value,format_text)5、自定义函数一、内置函数法如图1所示,我们来将C12单元格中的数值转换为中文大写形式,并将结果保存在D12单元格中。

1、分别选中E13、F13、G13单元格,依次输入公式:=TEXT(INT(ABS(C12)),"[DBNum2]")=TEXT(INT(ABS(C12*10))-INT(ABS(C12))*10,"[DBNum2]")=TEXT(INT(ABS(C12*100))-INT(ABS(C12*10))*10,"[DBNum2]")公式含义解析:分别确定统计结果的元、角、分的数值,并将其转换为中文大写格式。

2、选中E10单元格,输入公式:=E13&"元"&F13&"角"&G13&"分",或者:=CONCATENATE(E13,"元",F13,"角",G13,"分")。

公式含义解析:将E13至G13单元格中的文本组合为一个整体,并在相应位置加上单位“元、角、分”文字。

3、再次选中E12单元格,执行“格式→条件格式”命令,打开“条件格式”对话框(如图2)。

按“条件1”下面的下拉按钮,选中“公式”选项,在后面的方框中输入“=$C$12<0”(如图2),再按“格式”按钮,在随后弹出的“单元格格式”对话框中(如图3),将“字体”颜色设置为红色,确定退出。

数字转中文算法

数字转中文算法

数字转中文算法数字转中文算法是指将阿拉伯数字转换为中文的一种算法。

这种算法在中文计算机输入法、电子设备屏幕显示等场景中得到广泛应用。

该算法的实现方式主要分为以下两种:一、词法分析法这种算法将阿拉伯数字的每一位分别转换成相应的中文数字,再根据数字所处的位置加上相应的权值,最后将每个数字的中文表示合并起来即可。

具体实现步骤如下:1. 定义一个数组,分别用中文字符表示数字0-9:const char* CHINESE_NUMBERS[] = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};2. 将阿拉伯数字按位分离成一个数组,即数字的个位、十位、百位等。

3. 对于每个数字位,求出它的权值,然后将权值和中文数字合并成一个字符串。

4. 最后将转换后的字符串按照顺序合并起来。

二、递归除法法这种算法是一种递归算法,它的基本思路是将数字按位拆分,每次对10取余得到数的个位数,然后递归对此结果进行操作,得到十位以上的数的中文表示,最后将各部分中文表示拼接起来。

该算法的实现步骤如下:1. 定义一个数组,包含中文数字、零和一些特殊字符的中文表示。

2. 对输入的数字取余,并将余数作为数组下标,得到当前位数的中文表示,然后递归调用算法处理高位数字。

3. 注意,需要考虑一些特殊的数字,如1-10、100、1000、亿等,这些数字的特殊表示需要事先处理好。

无论采用哪种算法,数字转中文的实现都很简单。

在实际应用中,我们需要根据具体场景选择最适合的算法,以满足高效、准确地转换数字。

java程序练习:输入数字转换成中文输出(金额相关)

java程序练习:输入数字转换成中文输出(金额相关)

java程序练习:输⼊数字转换成中⽂输出(⾦额相关)//题⽬,做⼀个输⼊⾦额数字,输出转换成中⽂的⾦额名称。

public class Test {public static void main(String[] args) {System.out.println("欢迎使⽤数字转换器(Designed by wujj)!!");String in;boolean isRunning = true;Scanner scanner = new Scanner(System.in);while (isRunning) {System.out.println("请输⼊⼀串纯整数:");in = scanner.next();String input = in.trim();if (!isNum(input)) {System.out.println("输⼊类型错误!!!你应该输⼊12位以内纯正整数!!!");continue;} else {System.out.println("转换成中⽂数字为:" + num2Ch(input));}System.out.println("是否继续查询? 1.是 2.不,谢谢");int isContinue = scanner.nextInt();if (isContinue == 1) {continue;} else if (isContinue == 2) {System.out.println("程序结束!欢迎下次使⽤!!!");isRunning = !isRunning;} else {System.out.println("指令输⼊错误,直接退出!!");System.out.println("程序结束!欢迎下次使⽤!!!");isRunning = !isRunning;}}System.out.println("请输⼊任意数字退出控制台...");in = scanner.next();scanner.close();}private static String num2Ch(String input) {input = Long.parseLong(input) + "";if (input.equals("0")) {return "零";}// int length = input.length();// char[] arr1 = { 'O', '⼀', '⼆', '三', '四', '五', '六', '七', '⼋', '九', '⼗', '百',// '千', '万', '亿' };// char[] arr2 = { '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖', '拾', '佰',// '仟', '万', '亿' };StringBuffer s = new StringBuffer();switch (4 - (input.length() % 4)) {case 1:s = new StringBuffer("0").append(input);break;case 2:s = new StringBuffer("00").append(input);break;case 3:s = new StringBuffer("000").append(input);break;default:s = new StringBuffer("").append(input);}String[] arr = new String[s.length() / 4];for (int i = 0; i < s.length(); i = i + 4) {if (i + 4 == s.length())arr[i / 4] = s.toString().substring(i);elsearr[i / 4] = s.toString().substring(i, i + 4);}StringBuffer output = new StringBuffer("");switch (s.length() / 4) {case 3:output = output.append(trans(arr[s.length() / 4 - 3])).append("亿");case 2:if (Integer.parseInt(arr[s.length() / 4 - 2]) == 0 && Integer.parseInt(arr[s.length() / 4 - 3]) != 0)output = output.append("零");elseoutput = output.append(trans(arr[s.length() / 4 - 2])).append("万");case 1:output = output.append(trans(arr[s.length() / 4 - 1]));break;}return output.toString();}// 四位数转换函数private static String trans(String string) {String s = Integer.parseInt(string) + "";StringBuffer output = new StringBuffer("");String[] arr = { "", "⼀", "⼆", "三", "四", "五", "六", "七", "⼋", "九" };// for (int i = 0; i < s.length(); i++) {// if (s.charAt(i) != 0) {// s = s.substring(i);// break;// }// }if ((Integer.parseInt(s) + "").equals("")) {return "";} else {switch (s.length()) {case 4:if (Integer.parseInt(string.charAt(0) + "") == 0) {output = output.append("零");}else {output = output.append(arr[Integer.parseInt(s.charAt(0) + "")]).append("千");}case 3:if (Integer.parseInt(string.charAt(3) + "") != 0 && Integer.parseInt(string.charAt(1) + "") == 0 && Integer.parseInt(string.charAt(0) + "") != 0) { output = output.append("零");}else {output = output.append(arr[Integer.parseInt(string.charAt(1) + "")]);}if (Integer.parseInt(string.charAt(1) + "") != 0) {output = output.append("百");}case 2:if (Integer.parseInt(string.charAt(3) + "") != 0 && Integer.parseInt(string.charAt(2) + "") == 0 && Integer.parseInt(string.charAt(1) + "") != 0 && Integer.parseInt(string.charAt(0) + "") != 0) {output = output.append("零");}else{output = output.append(arr[Integer.parseInt(string.charAt(2) + "")]);}if (Integer.parseInt(string.charAt(2) + "") != 0) {output = output.append("⼗");}case 1:if (Integer.parseInt(string.charAt(3) + "") != 0) {output = output.append(arr[Integer.parseInt(string.charAt(3) + "")]);}break;}return output.toString();}}// 判断是否是纯数字输⼊private static boolean isNum(String s) {String num = "0123456789";int length = 0;for (int i = 0; i < s.length(); i++) {for (int j = 0; j < num.length(); j++) {if (s.charAt(i) == num.charAt(j)) {length++;break;}}}return (s.trim().length() != 0 && length == s.length() && length <= 12 && length >= 0) ? true : false;}}。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

package test.format;import java.text.NumberFormat;import java.util.HashMap;public class SimpleMoney Format {public static final String EMPTY = "";public static final String ZERO = "零";public static final String ONE = "壹";public static final String TWO = "贰";public static final String THREE = "叁";public static final String FOUR = "肆";public static final String FIVE = "伍";public static final String SIX = "陆";public static final String SEVEN = "柒";public static final String EIGHT = "捌";public static final String NINE = "玖";public static final String TEN = "拾";public static final String HUNDRED = "佰";public static final String THOUSAND = "仟";public static final String TEN_THOUSAND = "万";public static final String HUNDRED_MILLION = "亿";public static final String YUAN = "元";public static final String JIAO = "角";public static final String FEN = "分";public static final String DOT = ".";private static SimpleMoney Format formatter = null;private HashMap chineseNumberMap = new HashMap();private HashMap chineseMoney Pattern = new HashMap();private NumberFormat numberFormat = NumberFormat.getInstance(); private SimpleMoneyFormat() {numberFormat.setMaximumFractionDigits(4);numberFormat.setMinimumFractionDigits(2);numberFormat.setGroupingUsed(false);chineseNumberMap.put("0", ZERO);chineseNumberMap.put("1", ONE);chineseNumberMap.put("2", TWO);chineseNumberMap.put("3", THREE);chineseNumberMap.put("4", FOUR);chineseNumberMap.put("5", FIVE);chineseNumberMap.put("6", SIX);chineseNumberMap.put("7", SEVEN);chineseNumberMap.put("8", EIGHT);chineseNumberMap.put("9", NINE);chineseNumberMap.put(DOT, DOT);chineseMoney Pattern.put("1", TEN);chineseMoney Pattern.put("2", HUNDRED);chineseMoney Pattern.put("3", THOUSAND);chineseMoney Pattern.put("4", TEN_THOUSAND);chineseMoney Pattern.put("5", TEN);chineseMoney Pattern.put("6", HUNDRED);chineseMoney Pattern.put("7", THOUSAND);chineseMoney Pattern.put("8", HUNDRED_MILLION);}public static SimpleMoneyFormat getInstance() {if (formatter == null)formatter = new SimpleMoneyFormat();return formatter;}public String format(String money Str) {checkPrecision(money Str);String result;result = convertToChineseNumber(money Str);result = addUnitsToChineseMoney String(result);return result;}public String format(double money Double) {return format(numberFormat.format(money Double));}public String format(int moneyInt) {return format(numberFormat.format(moneyInt));}public String format(long money Long) {return format(numberFormat.format(money Long));}public String format(Number money Num) {return format(numberFormat.format(money Num));}private String convertToChineseNumber(String money Str) {String result;StringBuffer cMoney StringBuffer = new StringBuffer();for (int i = 0; i < money Str.length(); i++) {cMoney StringBuffer.append(chineseNumberMap.get(money Str.substring(i, i + 1)));}//拾佰仟万亿等都是汉字里面才有的单位,加上它们int indexOfDot = cMoney StringBuffer.indexOf(DOT);int money PatternCursor = 1;for (int i = indexOfDot - 1; i > 0; i--) {cMoney StringBuffer.insert(i, chineseMoney Pattern.get(EMPTY + money PatternCursor)); money PatternCursor = money PatternCursor == 8 ? 1 : moneyPatternCursor + 1;}String fractionPart = cMoney StringBuffer.substring(cMoney StringBuffer.indexOf(".")); cMoney StringBuffer.delete(cMoney StringBuffer.indexOf("."), cMoney StringBuffer.length()); while (cMoney StringBuffer.indexOf("零拾") != -1) {cMoney StringBuffer.replace(cMoney StringBuffer.indexOf("零拾"), cMoney StringBuffer.indexOf("零拾") + 2, ZERO);}while (cMoney StringBuffer.indexOf("零佰") != -1) {cMoney StringBuffer.replace(cMoney StringBuffer.indexOf("零佰"), cMoney StringBuffer.indexOf("零佰") + 2, ZERO);}while (cMoney StringBuffer.indexOf("零仟") != -1) {cMoney StringBuffer.replace(cMoney StringBuffer.indexOf("零仟"), cMoney StringBuffer.indexOf("零仟") + 2, ZERO);}while (cMoney StringBuffer.indexOf("零万") != -1) {cMoney StringBuffer.replace(cMoney StringBuffer.indexOf("零万"), cMoney StringBuffer.indexOf("零万") + 2, TEN_THOUSAND);}while (cMoney StringBuffer.indexOf("零亿") != -1) {cMoney StringBuffer.replace(cMoney StringBuffer.indexOf("零亿"), cMoney StringBuffer.indexOf("零亿") + 2, HUNDRED_MILLION);}while (cMoney StringBuffer.indexOf("零零") != -1) {cMoney StringBuffer.replace(cMoney StringBuffer.indexOf("零零"), cMoney StringBuffer.indexOf("零零") + 2, ZERO);}if (cMoney stIndexOf(ZERO) == cMoney StringBuffer.length() - 1)cMoney StringBuffer.delete(cMoney StringBuffer.length() - 1, cMoney StringBuffer.length()); cMoney StringBuffer.append(fractionPart);result = cMoney StringBuffer.toString();return result;}private String addUnitsToChineseMoney String(String money Str) {String result;StringBuffer cMoney StringBuffer = new StringBuffer(money Str);int indexOfDot = cMoney StringBuffer.indexOf(DOT);cMoney StringBuffer.replace(indexOfDot, indexOfDot + 1, Y UAN);。

相关文档
最新文档