数字转换大写核心类
听见有人在面试时遇到这样的问题:输入12345 输出一万两千三百四十五,如何做?
然后没事就写了一下:发给他们了。
代码如下:
package cc.makalu.transform; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; /** * * @ClassName:NumberToCapital * @Package:cc.makalu.transform * @Description:数字转换大写核心类 * @author:ljl * @version:v0.1 * @data:2017年10月16日 下午3:54:36 * 备注: */ public class NumberToCapital { private static String[] transform={"十", "百", "千", "万"}; private static Object[][] capitals= {{1,"一"},{2,"二"},{3,"三"},{4,"四"},{5,"五"},{6,"六"},{7,"七"},{8,"八"},{9,"九"},{0,"零"}}; /** * 数字转换大写方法 * @Title: num_capital * @Description: <p>数字转换大写方法:例如 输入12345输出一万两千三百四十五</p> * @return: String * @throws * @param number * @return */ public static String num_capital(int num) throws NumberFormatException { int i = 0; Map<Object, Object> map = new HashMap<>(); StringBuilder sb = new StringBuilder(); while(num > 0 && i <= transform.length) { int a = num % 10; num = num / 10; if(i == 0) { sb.append(findByNum(a, capitals)); } else { sb.append(transform[i-1]+""+findByNum(a, capitals)); } i++; } return sb.reverse().toString(); } /** * * @Title: findByNum * @Description: 根据个位数字返回大写的数字 * @return: String * @throws * @param num * @param capitals * @return */ public static String findByNum(int num, Object[][] capitals) { String str = ""; //循环 for(int i = 0; i < capitals.length; i++) { for(int j = 0; j < capitals[i].length; j++) { if(num == (Integer)capitals[i][0]) { str = (String)capitals[i][1]; } } } return str; } public static void main(String[] args) { System.out.println(num_capital(2345)); } }
已有注释我就不多说了。有需要可以参考!