程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA編程入門知識 >> java實現浮點數轉人民幣的小例子

java實現浮點數轉人民幣的小例子

編輯:JAVA編程入門知識

代碼如下:

import java.util.ArrayList;
import java.util.List;

public class RMBConverter2 implements IRMBConverter {

    private static final String [] RMB_NUMBER ={"零","壹","貳","三","肆","伍","陸","柒","捌","玖"};

    private static final String [] RMB_ATTR = {"元","十","佰","仟","萬","十","百","仟","億","十","佰","仟","萬","十","佰","仟"};

    private static final String[] RMB_FEN = {"分","角"};

     
    @Override
    public String change2RMB(double counts) {
        StringBuffer rsBuf = new StringBuffer();

        if (counts == 0L) {
            return "零";
        }

        if (counts < 0) 
            rsBuf.append("負");

        String zheng = strConverse(String.valueOf((long)counts));
        String xiao = strConverse(String.valueOf(Math.round((counts - (long)counts)*100)));

        char [] zhengArray = zheng.toCharArray();
        char [] xiaoArray = xiao.toCharArray();

        int zLength = zhengArray.length;
        int xLength = xiaoArray.length;

        List<String> zhengList = new ArrayList<String>();

        for(int i =0; i< zLength; i++) {
            int value = Integer.parseInt(""+zhengArray[i]);
            if (value == 0 && (i != 4) && (i != 8) && i != 0) {
                zhengList.add(RMB_NUMBER[value]);
            }else {
                zhengList.add(RMB_NUMBER[value]+
                     RMB_ATTR[i]);
            }
        }

        for(int i = zhengList.size()-1; i>=0; i--) {
            rsBuf.append(zhengList.get(i));
        }

         
        for(int i =0; i<xLength ;i++) {
            int value = Integer.parseInt(""+xiaoArray[i]);
            if (value > 0 ) {
                rsBuf.append(RMB_NUMBER[value])
                 .append(RMB_FEN[xLength-i-1]);
            }
        }

        String rs = rsBuf.toString();
        rs = rs.replaceAll("零+", "零");
        rs = rs.replaceAll("零元", "元");
        rs = rs.replaceAll("零萬", "萬");
        rs = rs.replaceAll("零億", "億");
        rs = rs.replaceAll("億萬", "億");
        return rs;
    }

     
    private String strConverse(String str) {
        StringBuffer rs = new StringBuffer();
        char [] strArray = str.toCharArray();
        for(int i = str.length()-1; i>=0; i--) {
            rs.append(strArray[i]);
        }
        return rs.toString();
    }

     
    public static void main(String args []) {

        RMBConverter2 c2 = new RMBConverter2();
        System.out.println(c2.change2RMB(2001004.10));
        System.out.println(c2.change2RMB(2000000.10));
        System.out.println(c2.change2RMB(0L));
        System.out.println(c2.change2RMB(1121000010000000L));
    }

}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved