告诉你什么是优雅的代码(6)------阿拉伯钱数转换为中文形式
编程技术  /  houtizong 发布于 3年前   75
public class MoneyTrans {private static String[] ChinaDigit = {"零","一","二","三","四","五","六","七","八","九"};private static String[] UNIT = {"","","十","百","千"};private static String[] BIGUNIT = {"","万","亿","兆"};private static long MAX = 10000000000000000L - 1;private char[] digit;public String trans(long n) throws Exception{if(n > MAX){throw new Exception("数字过大,最多可处理到千兆位");}StringBuffer buff = new StringBuffer();boolean isPrePartZero = false;digit = String.valueOf(n).toCharArray();int length = digit.length;int pos = (length - 1)/4;int headLength = (length - 1)%4 + 1;// xxxxxxxxxx --> xx|xxxx|xxxxbuff.append(partTrans(0,headLength) + BIGUNIT[pos--]);for (int i = headLength;i < length ; i = i + 4) {String part = partTrans(i , i + 4);if(part.length() == 0){isPrePartZero = true;}else{if(isPrePartZero && !part.startsWith(ChinaDigit[0])){buff.append(ChinaDigit[0]);}buff.append(part + BIGUNIT[pos]) ;isPrePartZero = false;}pos--;}return buff.toString();}private String partTrans(int start, int end) {StringBuffer buff = new StringBuffer();boolean isPreDigitZero = false;for (int i = start; i < end; i++) {int cur = digit[i] - '0';if(cur != 0 ){if(isPreDigitZero){buff.append(ChinaDigit[0]);}buff.append(ChinaDigit[cur] + UNIT[end - i]);isPreDigitZero = false;}else {isPreDigitZero = true;}}return buff.toString();}public static void main(String[] args) throws Exception {MoneyTrans transtor = new MoneyTrans(); String money = transtor.trans(9000000000000000L);System.out.println(money);}}
九千兆
请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!
技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成
网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];
文章归档
文章标签
友情链接