首页 > 代码库 > 金额转换成大写
金额转换成大写
import java.text.DecimalFormat; import java.util.Scanner; /** * @Description: 金额转换成大写 * @author huangzjb * @mail cblue2013@126.com * @Company Digital China * @date 2015-1-30 */ public class ChineseCurrency { public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.println("请输入人民币金额:"); while (true) { double number = s.nextDouble(); if(number > 10000000000000000.0) { System.out.println("金额太大,超出16位最大的整数!"); continue; } System.out.println(toChineseCurrency(new Double(number))); } } public static String toChineseCurrency(Number number) { String targetNumber = new DecimalFormat("#.00").format(number); String result = ""; targetNumber = targetNumber.replaceAll("\\.", ""); char[] digit = { '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖' }; String unit = "仟佰拾兆仟佰拾亿仟佰拾万仟佰拾元角分"; int unitLength = unit.length(); StringBuffer unitSb = new StringBuffer(unit); StringBuffer resultSb = new StringBuffer(result); for (int i = targetNumber.length() - 1; i >= 0; i--){ resultSb = unitSb.insert(unitLength - targetNumber.length() + i, digit[(targetNumber.charAt(i) - 0x30)]);//根据金额数字所在的位置,把它们对应的大写汉字和后面的单位('万仟佰拾...')拼接起来 } result = resultSb.toString(); //System.out.println((l + s.length() )== sb.length()); result = result.substring(unitLength - targetNumber.length(), unitLength + targetNumber.length());//根据金额数字的长度,把前面超出范围的单位截掉(比如234.12,要把前面的'仟佰拾兆仟佰拾亿仟佰拾万仟'去掉..) //System.out.println(result); /*result = result.replaceAll("零[拾佰仟]", "零").replaceAll("零{2,}", "零") .replaceAll("零([兆亿万元])", "$1").replaceAll("零[角分]", "");*/ result = result.replaceAll("零[拾佰仟]", "零") .replaceAll("零{2,}", "零")//有多个零连在一起,只取一个零 .replaceAll("([拾佰仟])零([兆亿万])", "$1$2")//可以理解为把金额从低位到高位分为四组,每组四位,这一步是去除每一组(不全为零)末尾的零 .replaceAll("零[兆亿万]", "")//处理四位数全为零的组 .replaceAll("零元", "元"). replaceAll("零[角分]", ""); if (result.endsWith("角")) result += "零分"; if (!result.contains("角") && !result.contains("分") && result.contains("元")) result += "整"; if (result.contains("分") && !result.contains("整") && !result.contains("角")) result = result.replace("元", "元零"); return result; } }
金额转换成大写
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。