android app中用到的金额操作类

来源:互联网 发布:数据库自学 书籍 编辑:程序博客网 时间:2024/05/17 23:13

Android app中用到的金额操作类

1.app接口定义时涉及到的金额都以分为单位,只有最后在app上显示时才转为元。这样既方便程序中对价格的运算,也便于以后对价格的扩展。下面提供 分转元 和 元转分的转换方法。注意金额计算要用 BigDecimal来进行精确的运算。

/**      * @Method     : fen2yuan      * @Description: 单位转换:分转元     * @param money     * @return     */    public static String fen2yuan(int money) {        BigDecimal bigMoney = new BigDecimal(String.valueOf(money));        BigDecimal feedRate = new BigDecimal("100");        String returnStr = String.valueOf(bigMoney.divide(feedRate).setScale(2));        if (returnStr.indexOf(".") > 0) {            //正则表达            returnStr = returnStr.replaceAll("0+?$", "");//去掉后面无用的零            returnStr = returnStr.replaceAll("[.]$", "");//如小数点后面全是零则去掉小数点        }        return returnStr;    }
/**      * @Method     : yuan2fen      * @Description: 单位转换:元转分     * @param money     * @return     */    public static String yuan2fen(String money) {        String returnMoney = "";        if (isNumber(money)) {            BigDecimal feedRate = new BigDecimal(100);            returnMoney = new BigDecimal(money).multiply(feedRate).setScale(0).toString();        }        return returnMoney;    }    /**      * @Method     : isNumber      * @Description: 判断是否为金额     * @param str     * @return     */    public static boolean isNumber(String str) {        java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$"); // 判断小数点后2位的数字的正则表达式          java.util.regex.Matcher match = pattern.matcher(str);        return match.matches();    }
2.在做报表统计时,需要用到金额大写。下面提供该工具类:
public class MoneyUtil {    private static final Pattern AMOUNT_PATTERN = Pattern.compile("^(0|[1-9]\\d{0,11})\\.(\\d\\d)$"); // 不考虑分隔符的正确性    private static final char[] RMB_NUMS = "零壹贰叁肆伍陆柒捌玖".toCharArray();    private static final String[] UNITS = { "元", "角", "分", "整" };    private static final String[] U1 = { "", "拾", "佰", "仟" };    private static final String[] U2 = { "", "万", "亿" };    /**      * @Method     : convert      * @Description: 将金额(整数部分等于或少于12位,小数部分2位)转换为中文大写形式.     * @param amount     * @return     * @throws IllegalArgumentException     */    public static String convert(String amount) throws IllegalArgumentException {        // 去掉分隔符        amount = amount.replace(",", "");        // 验证金额正确性        if (amount.equals("0.00")) {            throw new IllegalArgumentException("金额不能为零.");        }        Matcher matcher = AMOUNT_PATTERN.matcher(amount);        if (!matcher.find()) {            throw new IllegalArgumentException("输入金额有误.");        }        String integer = matcher.group(1); // 整数部分        String fraction = matcher.group(2); // 小数部分        String result = "";        if (!integer.equals("0")) {            result += integer2rmb(integer) + UNITS[0]; // 整数部分        }        if (fraction.equals("00")) {            result += UNITS[3]; // 添加[整]        } else if (fraction.startsWith("0") && integer.equals("0")) {            result += fraction2rmb(fraction).substring(1); // 去掉分前面的[零]        } else {            result += fraction2rmb(fraction); // 小数部分        }        return result;    }    /**      * @Method     : fraction2rmb      * @Description: 将金额小数部分转换为中文大写     * @param fraction     * @return     */    private static String fraction2rmb(String fraction) {        char jiao = fraction.charAt(0); // 角        char fen = fraction.charAt(1); // 分        return (RMB_NUMS[jiao - '0'] + (jiao > '0' ? UNITS[1] : "")) + (fen > '0' ? RMB_NUMS[fen - '0'] + UNITS[2] : "");    }    /**      * @Method     : integer2rmb      * @Description: 将金额整数部分转换为中文大写     * @param integer     * @return     */    private static String integer2rmb(String integer) {        StringBuilder buffer = new StringBuilder();        // 从个位数开始转换        int i, j;        for (i = integer.length() - 1, j = 0; i >= 0; i--, j++) {            char n = integer.charAt(i);            if (n == '0') {                // 当n是0且n的右边一位不是0时,插入[零]                if (i < integer.length() - 1 && integer.charAt(i + 1) != '0') {                    buffer.append(RMB_NUMS[0]);                }                // 插入[万]或者[亿]                if (j % 4 == 0) {                    if (i > 0 && integer.charAt(i - 1) != '0' || i > 1 && integer.charAt(i - 2) != '0' || i > 2 && integer.charAt(i - 3) != '0') {                        buffer.append(U2[j / 4]);                    }                }            } else {                if (j % 4 == 0) {                    buffer.append(U2[j / 4]); // 插入[万]或者[亿]                }                buffer.append(U1[j % 4]); // 插入[拾]、[佰]或[仟]                buffer.append(RMB_NUMS[n - '0']); // 插入数字            }        }        return buffer.reverse().toString();    }    /**      * @Method     : moneyFormat      * @Description: 对金额的格式调整到分     * @param money     * @return     */    public static String moneyFormat(String money) {// 23->23.00        StringBuffer sb = new StringBuffer();        if (money == null) {            return "0.00";        }        while (money.startsWith("0")) {            money = money.substring(1);        }        int index = money.indexOf(".");        if (index == -1) {            return money + ".00";        } else {            String s0 = money.substring(0, index);// 整数部分            String s1 = money.substring(index + 1);// 小数部分            if (s1.length() == 1) {// 小数点后一位                s1 = s1 + "0";            } else if (s1.length() > 2) {// 如果超过3位小数,截取2位就可以了                s1 = s1.substring(0, 2);            }            sb.append(s0);            sb.append(".");            sb.append(s1);        }        return sb.toString();    }    public static void main(String[] args) {        System.out.println(MoneyUtil.moneyFormat("123.2883"));        System.out.println(MoneyUtil.convert(MoneyUtil.moneyFormat("50200300.2883")));    }}

3.另外附一些金额格式话的代码片段:
a.金额11112345.12345 格式化显示为: 11,112,345.123

        DecimalFormat myformat = new DecimalFormat();        myformat.applyPattern("##,###.000");        System.out.println(myformat.format(11112345.12345));

b.金额保留两位小数显示

    double f = 111231;    public void m1() {        DecimalFormat df = new DecimalFormat("#.00");        System.out.println(df.format(f));    }
1 0