金额转换常用方法

   不管是做银行的接口,还是一般支付公司的接口,都会用到一些
相关的接口,一般接口对传递的金额都会有相关的要求,一般都是以
分为单位,要转换其实并不难,但很多情况下就是怕出错,钱啊!!
所以小心了还得小心,金额中最忌讳的就是double和int的混合运算
了,本机上不出问题,草草测试的后果就不堪设想,用户的数据千奇
百怪,一不小心就是大问题,我这里写了两个常用的方法,我的想法
是减少运算,尽量是字符串操作,减少出错!仅供参考!

希望在这里能抛砖引玉!

    /**
     * 将以分为单位的字符串转换为double类型
     * @param s
     * @return
     */
    public static double str2Double(String s) {
        double r = 0.0;
        int k = Integer.parseInt(s);
        String ss = String.format("%1$012d", k);
        System.out.println(ss);
       
        StringBuffer sb = new StringBuffer();
        sb.append(ss.substring(0, 10));
        sb.append(".");
        sb.append(ss.substring(10));
       
        r = Double.parseDouble(sb.toString());
        return r;
    }
   
    /**
     * 拿取去掉小数点的金额
     * @param amount
     * @return
     */
    public static String getAmountStr(double amount) {
        //amount*100不能超过int的最大值     订单交易金额,12位长度,左补0,必填,单位为分
        String TransAmt = "";
        String amountStr = amount+"";
        int _tempAmt = Integer.parseInt(amountStr.replaceAll("\\.",""));
        if(amountStr.matches("[0-9]+\\.[0-9]{2}")){
            TransAmt = String.format("%1$012d", _tempAmt);
        } else if(amountStr.matches("[0-9]+\\.[0-9]{1}")) {
            TransAmt = String.format("%1$011d0", _tempAmt);
        } else if(amountStr.matches("[0-9]+")) {
            TransAmt = String.format("%1$010d00", _tempAmt);
        }
        return TransAmt.replaceAll("^0+", "");
    }

猜你喜欢

转载自jayo.iteye.com/blog/557671