zoukankan      html  css  js  c++  java
  • 人民币处理问题(原创)

    1, 人民币小写转为大写

      private static Map<Integer,String> map2UpperWeight =null;
        
        static{
            map2UpperWeight=new HashMap<Integer,String>();
            map2UpperWeight.put(0, "分");
            map2UpperWeight.put(1, "角");
            map2UpperWeight.put(2, "元");
            map2UpperWeight.put(3, "拾");
            map2UpperWeight.put(4, "佰");
            map2UpperWeight.put(5, "仟");
            map2UpperWeight.put(6, "万");
            map2UpperWeight.put(7, "拾");
            map2UpperWeight.put(8, "佰");
            map2UpperWeight.put(9, "仟");
            map2UpperWeight.put(10, "亿");
            map2UpperWeight.put(11, "拾");
            map2UpperWeight.put(12, "佰");
            map2UpperWeight.put(13, "仟");
        
        }
      /**
         * yangw
         * 小写金额转换为大写金额
         * 123,344.60-->壹拾贰万叁仟叁佰肆拾肆元陆角.
         */
        public static String toUpperMoney(String str){
            //1,倒序
            str=str.replaceAll("\.", "").replaceAll(",", ""); 
            str=new StringBuffer(str).reverse().toString();
            
            // 是否是零
            boolean isZero=false;
            //是否是末尾零
            boolean isLastZero=false;
            //结果buffer
            StringBuffer result=new StringBuffer();
            //循环迭代
            for(int i=0;i<str.length();i++){
                char ch=str.charAt(i);
                
                //检查零
                if(ch=='0'){
                    //如果result中没有任何字符,那么这个零玖拾末尾零
                    if(result.length()==0)isLastZero=true;
                    isZero=true;
                    continue;
                }else{
                    
                    if(isZero){ //有零时,应该加入零
                        isZero=false;
                        if(isLastZero){ //末尾零不加入
                            isLastZero=false;
                        }else{
                            result.append("零");
                        }    
                    }
                    if(i>2){
                        if(result.indexOf("元")==-1){
                            result.append("元");
                        }
                    }
                    //先加入权重
                    if(i>6&&i<10){ //可能需要加入 "万"
                        if(result.indexOf("万")==-1){
                            result.append("万");
                        }
                    }else if(i>10){
                        if(result.indexOf("亿")==-1){
                            result.append("亿");
                        }
                    }
                    result.append(map2UpperWeight.get(i));
                    switch (ch) {
                            
                        case '1':
                            result.append("壹");
                        break;
                        case '2':
                            result.append("贰");
                            break;
                        case '3':
                            result.append("叁");
                            break;
                        case '4':
                            result.append("肆");
                            break;
                        case '5':
                            result.append("伍");
                            break;
                        case '6':
                            result.append("陆");
                            break;
                        case '7':
                            result.append("柒");
                            break;
                        case '8':
                            result.append("捌");
                            break;
                        case '9':
                            result.append("玖");
                            break;
                        default:
                        break;
                    }
                    
                }    
            }
            //是否加入整
            String temp=result.toString();
            if(!(temp.startsWith("角") || temp.startsWith("分")))
                result.insert(0, "整");
            
            return result.reverse().toString();
        }
        

    2, 其他人民币的处理

    /**
         * yangw
         * 处理金额字段(去掉小数点,如果是人民币最后两位是角分)
         * 123,344.60-->000012334460
         * @param str
         * @return
         */
        public static String preAmount(String str){
            //1,确定小数点的位置
            int len=str.length();
            int index=str.indexOf(".");
            //2,小数点后面有几位
            if(index==-1){
                str+="00";
            }else if(len-index-1==1){
                str+="0";
            }
            //去掉小数点,去掉逗号
            str=str.replaceAll("\.", "").replaceAll(",", ""); 
            str=StringUtil.fillChar(str, '0', 12, true);
            
            return str;
        }
    
        /**
         * yangw
         * 还原真实的金额,(即加入小数点,去掉前面补的零) 
         * 比如 :000003452312-->34523.12
         */
        public static String restoreAmount(String str){
            //1, 去掉前面的零
            Pattern pat = Pattern.compile("^0+");  
            Matcher mat = pat.matcher(str);  
            if( mat.find()){
                str=mat.replaceFirst("");
            }
            if("".equals(str)){
                str="0";
            }
            
            //2,加入小数点, 办法(数字乘以0.01)
            double temp=Double.parseDouble(str);
            if(temp==0) return "0.00";
            double result=temp*0.01;
            
            //3,格式化数字 为两位小数
            //#.00 表示两位小数 #.0000四位小数 以此类推...
            DecimalFormat df =new DecimalFormat("#.00");  
            df.format(result);
            return df.format(result);
        }
        
        /**
         * yangw
         * 真实的金额(含有千分位),(即加入小数点,去掉前面补的零,并且加入千分位) 
         * 比如 :000003452312-->34,523.12
         */
        public static String thousandsAmount(String str){
            //先去掉前面的零和加入小数点
            str=restoreAmount(str); 
            //123.45 这样的数字不需要处理
            if(str.length()<7) return str;
            //小数点取前面部分和后面部分
            String preStr=str.substring(0, str.length()-3);
            String lastStr=str.substring(str.length()-3);
            //为前面部分的数字加入千分位
            StringBuffer sb=new StringBuffer();
            //i表示当前子串的开始位置,j表示当前子串的结束位置
            int j=preStr.length();
            for(int i=preStr.length()-3;i>0;j=i,i-=3){
                sb.insert(0, ","+preStr.substring(i, j));//插入最前面
            }
            sb.insert(0,preStr.substring(0,j));//(0,j)最后一次的需要额外加入
            sb.append(lastStr);
            return sb.toString();
        }

    ============================2018年新版本人民币金额大小写转换功能Java实现========================================

      1 package hulk.yangw.support;
      2 
      3 import java.math.BigDecimal;
      4 import java.math.BigInteger;
      5 import java.text.DecimalFormat;
      6 import java.text.ParseException;
      7 import java.util.HashMap;
      8 import java.util.Map;
      9 
     10 /**
     11  * 金额工具类
     12  * @author yangw
     13  * @date   2018-07-05
     14  */
     15 public class MoneyUtil {
     16 
     17     /**
     18      * 默认格式
     19      */
     20     static String DEFAULT_PATTERN = ",###,##0.00";
     21     
     22     
     23     private static Map<Integer,Character> map2UpperWeight =null;
     24     
     25     static{
     26         map2UpperWeight=new HashMap<Integer,Character>();
     27         map2UpperWeight.put(0, '分');
     28         map2UpperWeight.put(1, '角');
     29         map2UpperWeight.put(2, '元');
     30         map2UpperWeight.put(3, '拾');
     31         map2UpperWeight.put(4, '佰');
     32         map2UpperWeight.put(5, '仟');
     33         map2UpperWeight.put(6, '万');
     34         map2UpperWeight.put(7, '拾');
     35         map2UpperWeight.put(8, '佰');
     36         map2UpperWeight.put(9, '仟');
     37         map2UpperWeight.put(10, '亿');
     38         map2UpperWeight.put(11, '拾');
     39         map2UpperWeight.put(12, '佰');
     40         map2UpperWeight.put(13, '仟');
     41         map2UpperWeight.put(14, '万');
     42         map2UpperWeight.put(15, '拾');
     43         map2UpperWeight.put(16, '佰');
     44         map2UpperWeight.put(17, '仟');
     45         
     46     }
     47     
     48     /**
     49      * 金额转换为千分位显示的金额值
     50      * @param srcMoney 传入的金额
     51      * @return
     52      */
     53     public static String toThousands(Object srcMoney ){
     54         Double money = toNumber(srcMoney);
     55         return toThousands(money,DEFAULT_PATTERN);
     56     }
     57 
     58     /**
     59      * 对象转为Double值
     60      * @param srcMoney
     61      * @return
     62      */
     63     private static Double toNumber(Object srcMoney){
     64         
     65         
     66         if(srcMoney == null) return null;
     67         if(srcMoney instanceof String){
     68             String temp = ((String) srcMoney).replaceAll(",", "");
     69             return Double.parseDouble(temp);
     70         }else if(srcMoney instanceof Integer){
     71             return (Integer)srcMoney*1.0;
     72         }else if(srcMoney instanceof BigDecimal){
     73             return ((BigDecimal)srcMoney).doubleValue();
     74         }else if(srcMoney instanceof BigInteger){
     75             return ((BigInteger)srcMoney).doubleValue();
     76         }else{
     77             return (Double)srcMoney;
     78         }
     79         
     80     }
     81     /**
     82      * 金额格式化显示
     83      * @param srcMoney 传入的金额
     84      * @param pattern 格式化串
     85      * @return
     86      */
     87     public static String toThousands(Object srcMoney,String pattern){
     88         Double money = toNumber(srcMoney);
     89         DecimalFormat df=new DecimalFormat(pattern); 
     90         //df.setRoundingMode(RoundingMode.FLOOR); //设置舍入方式
     91         return df.format(money);
     92     }
     93     
     94     /**
     95      * 千分位数字解析为普通数字显示
     96      * @param srcMoney 传入的千分位金额
     97      * @param pattern 格式化串
     98      * @return
     99      * @throws ParseException 
    100      */
    101     public static Double toNumeric(String srcMoney ,String pattern) throws Exception{
    102         
    103         DecimalFormat df=new DecimalFormat(pattern);
    104         return df.parse(srcMoney).doubleValue();
    105     }
    106     
    107     /**
    108      * 千分位数字解析为普通数字显示
    109      * @param srcMoney 传入的千分位金额
    110      * @throws ParseException 
    111      */
    112     public static Double toNumeric(String srcMoney) throws Exception{
    113         
    114         return toNumeric(srcMoney,DEFAULT_PATTERN);
    115     }
    116     
    117     /**
    118      * 小写金额转换为大写金额
    119      * 如:123,344.60-->壹拾贰万叁仟叁佰肆拾肆元陆角.
    120      */
    121     public static String toUpperMoney(Object srcMoney){
    122         //1, 将传入的对象格式化为标准的千分位形式
    123         String money = toThousands(srcMoney);    
    124         
    125         //2,倒序
    126         money=money.replaceAll("\.", "").replaceAll(",", ""); 
    127         money=new StringBuffer(money).reverse().toString();
    128         
    129         // 是否是零
    130         boolean isZero=false;
    131         //是否是末尾零
    132         boolean isLastZero=false;
    133         //结果buffer
    134         StringBuffer result=new StringBuffer();
    135         //循环迭代
    136         for(int i=0;i<money.length();i++){
    137             char ch=money.charAt(i);
    138             
    139             //检查零
    140             if(ch=='0'){
    141                 //如果result中没有任何字符,那么这个零就是末尾零
    142                 if(result.length()==0)isLastZero=true;
    143                 isZero=true;
    144                 continue;
    145             }else{
    146                 
    147                 if(isZero){ //有零时,应该加入零
    148                     isZero=false;
    149                     if(isLastZero){ //末尾零不加入
    150                         isLastZero=false;
    151                     }else{
    152                         result.append('零');
    153                     }    
    154                 }
    155                 if(i>2){
    156                     if(result.indexOf("元")==-1){
    157                         result.append('元');
    158                     }
    159                 }
    160                 //先加入权重
    161                 if(i>6&&i<10){ //可能需要加入 "万"
    162                     if(result.indexOf("万")==-1){
    163                         result.append('万');
    164                     }
    165                 }else if(i>10){
    166                     if(result.indexOf("亿")==-1){
    167                         result.append('亿');
    168                     }
    169                 }
    170                 result.append(map2UpperWeight.get(i));
    171                 switch (ch) {
    172                         
    173                     case '1':
    174                         result.append('壹');
    175                     break;
    176                     case '2':
    177                         result.append('贰');
    178                         break;
    179                     case '3':
    180                         result.append('叁');
    181                         break;
    182                     case '4':
    183                         result.append('肆');
    184                         break;
    185                     case '5':
    186                         result.append('伍');
    187                         break;
    188                     case '6':
    189                         result.append('陆');
    190                         break;
    191                     case '7':
    192                         result.append('柒');
    193                         break;
    194                     case '8':
    195                         result.append('捌');
    196                         break;
    197                     case '9':
    198                         result.append('玖');
    199                         break;
    200                     default:
    201                     break;
    202                 }
    203                 
    204             }    
    205         }
    206         //是否加入整
    207         String temp=result.toString();
    208         if(!(temp.startsWith("角") || temp.startsWith("分")))
    209             result.insert(0, '整');
    210         
    211         return result.reverse().toString();
    212     }
    213     
    214     
    215     /**
    216      * 大写金额转为小写金额<br/>
    217      * 完全使用Double因为精度问题,会出现 12131.45 --> 12131.449999999999,故改为用BigDecimal<br/>
    218      * 遇到百亿的数值会转为负数问题 ,所以大数字运算需要使用BigDecimal函数<br/>
    219      * 解决万亿的问题
    220      */
    221     public static Double toLowerMoney(String srcMoney){
    222     
    223         int currTextNum = 0;    //当前取到的值
    224         int tempResult = 0;        //临时结果(当遇到万 亿时临时结果清零)
    225         int tempCount = 0;         //临时结果清零的次数
    226         int weight = 0;         //连续权重的次数,遇到数字该值清零
    227         
    228         BigDecimal result = new BigDecimal(0);    //最终结果
    229         
    230          for(int i=0;i<srcMoney.length();i++){
    231              char ch=srcMoney.charAt(i);
    232              switch(ch){
    233              case '壹':
    234                  currTextNum = 1;
    235                  weight = 0;
    236                  break;
    237              case '贰':
    238                  currTextNum = 2;
    239                  weight = 0;
    240                  break;
    241              case '叁':
    242                  currTextNum = 3;
    243                  weight = 0;
    244                  break;
    245              case '肆':
    246                  currTextNum = 4;
    247                  weight = 0;
    248                  break;
    249              case '伍':
    250                  currTextNum = 5;
    251                  weight = 0;
    252                  break;
    253              case '陆':
    254                  currTextNum = 6;
    255                  weight = 0;
    256                  break;
    257              case '柒':
    258                  currTextNum = 7;
    259                  weight = 0;
    260                  break;
    261              case '捌':
    262                  currTextNum = 8;
    263                  weight = 0;
    264                  break;
    265              case '玖':
    266                  currTextNum = 9;
    267                  weight = 0;
    268                  break;  
    269              case '分':
    270                  result = result.add(new BigDecimal(currTextNum).multiply(new BigDecimal(0.01)));
    271                 break;
    272              case '角':
    273                  result = result.add(new BigDecimal(currTextNum).multiply(new BigDecimal(0.1)));
    274                  break;
    275              case '元':
    276                  weight++;
    277                  if(weight<=1){ // 如 1234
    278                      result = result.add(new BigDecimal(currTextNum));
    279                  }
    280                  result = result.add(new BigDecimal(tempResult));
    281                  currTextNum = 0;
    282                  
    283                  break;
    284              case '拾':
    285                  tempResult += currTextNum*10;
    286                  weight++;
    287                  break;
    288              case '佰':
    289                  tempResult += currTextNum*100;
    290                  weight++;
    291                  break;
    292              case '仟':
    293                  tempResult += currTextNum*1000;
    294                  weight++;
    295                  break;
    296              case '万':
    297                  tempCount++;
    298                  weight++;
    299                  BigDecimal bd_wan = new BigDecimal(10000);    //若直接用 *10000会出现超过精度而产生无法预估的数字
    300                  if(weight>1){
    301                      if(tempCount==1){    //说明首次遇到万
    302                          result = new BigDecimal(tempResult).multiply(bd_wan);
    303                      }else{
    304                  
    305                         result = result.add(new BigDecimal(tempResult).multiply(bd_wan));
    306                      }
    307                  }else{
    308                      if(tempCount==1){    //说明首次遇到万
    309                          result = new BigDecimal(currTextNum+tempResult).multiply(bd_wan);
    310                      }else{
    311                          result = result.add(new BigDecimal(currTextNum+tempResult).multiply(bd_wan));
    312                      }
    313                  }
    314                 
    315                  tempResult =0;
    316                  currTextNum = 0;
    317                  break;
    318              case '亿':
    319                  tempCount++;
    320                  weight++;
    321                  BigDecimal bd_yi = new BigDecimal(100000000);    //若直接用 *100000000会出现超过精度而产生无法预估的数字
    322                  if(weight>1){    //说明有类似百万这样形式的数据产生
    323                      if(tempCount==1){    //说明首次遇到亿
    324                          result = new BigDecimal(tempResult).multiply(bd_yi);
    325                      }else{ 
    326                          //解决万亿以上问题的写法
    327                          result = new BigDecimal(tempResult).add(result).multiply(bd_yi);
    328                      }
    329                  }else{
    330                      if(tempCount==1){    //说明首次遇到亿
    331                          result = new BigDecimal(currTextNum+tempResult).multiply(bd_yi);
    332                      }else{
    333                         //result = result.add(new BigDecimal(currTextNum+tempResult).multiply(bd_yi));
    334                         //解决万亿以上问题的写法
    335                          result = new BigDecimal(tempResult+currTextNum).add(result).multiply(bd_yi);
    336                      }
    337                  }
    338                  
    339                  tempResult = 0;
    340                  currTextNum = 0;
    341                  break;
    342              case '整':
    343              case '零':
    344                  weight = 0;
    345                  break;
    346              default:
    347                  System.out.println("无效字符:"+ch);
    348              }
    349          }
    350          
    351         return result.doubleValue();
    352     }
    353     
    354     
    355    
    356     public static void main(String[] args) throws Exception{
    357         
    358         String number = "10239400.00";
    359         String upper = toUpperMoney(number);
    360         System.out.println(number+"-->upper:" + upper);
    361         System.out.println("lower:" + toThousands(toLowerMoney(upper)));
    362     }
    363     
    364 }
    ----------- 赠人玫瑰,手有余香     如果本文对您有所帮助,动动手指扫一扫哟   么么哒 -----------


    未经作者 https://www.cnblogs.com/xin1006/ 梦相随1006 同意,不得擅自转载本文,否则后果自负
  • 相关阅读:
    Android 通过ViewFlipper实现广告轮播功能并可以通过手势滑动进行广告切换
    [C#][DevPress]自定义数据分页控件
    [C#][SQLLITE]一个数据分页技巧
    [C#]用SharpZipLib压缩多个文件
    [C#][DevPress]省市县乡嵌套查询
    [C#][DevPress]事件委托的使用
    [C#]Excel操作类
    [C#][DevPress]手动添加控件中的子控件或者结构
    [C#]XML操作类
    [C#]把DataTable转换成泛型实体List
  • 原文地址:https://www.cnblogs.com/xin1006/p/3523731.html
Copyright © 2011-2022 走看看